<?php
/**
 * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

/**
 * HTML5端 用户中心API文件
 * User: poptser
 * Email:poptser@foxmail.com
 * Date: 2016/8/13
 * Time: 10:25
 */

namespace SDXApi\Controller;
use SDXApi\Service\BuyNowGoodsService;
//use SDXApi\Service\Kingdee\GoodsStockQueryService;
use SDXApi\Service\PromoteService;
use SDXApi\Service\UserBonusService;
use Think\Cache\Driver\Redis;
use Think\Exception;
use Think\Model;
use SDXApi\Service\UserBehavior;
use SDXApi\Model\WorkorderModel;

class H5userController extends AppController
{
    public function _initialize($apptoken, $apptime)
    {
        parent::_initialize($apptoken, $apptime,true); // TODO: Change the autogenerated stub
    }

    /**
     *用户登录 API
     */
    public function user_login(){

        if(!empty($this->uid)){
            $users = M("users")->field("password,paypwd",true)->where(array("user_id"=>$this->uid))->find();

            if($users){
                $Return_data = $users;
                $wechat_user = M("wechat_user")->field("openid,nickname,headimgurl")->where(array("ect_uid"=>$this->uid))->find();

                //dump(M("wechat_user")->getlastsql());
                //dump($wechat_user);

                if($wechat_user){
                    $Return_data['nickName']= $wechat_user['nickname'];
                    $Return_data['headImage']= str_replace("http://", "https://", $wechat_user['headimgurl']);
                    $Return_data['openId']= $wechat_user['openid'];
                }
                $Return_data['Uid']= $this->uid;
                $Return_data['point']= $users['user_money'];
                $Return_data['phone']= $users['mobile_phone'];

                $Return_data['ucode']= md5($users['user_id'].'sdx@9999');

                $usersModel = D("Users");
                $usersModel->update_user_info($this->uid); //更新用户登录信息
//				if ($users['is_hd'] == '-1') {
//					$usersModel->update_user_is_hd_by_user_id($this->uid, $this->is_hd);
//				}


                //dump($Return_data);

                D("Sessions")->update_session($this->session_id,$this->uid,$this->max_life_time,$users['email'],$users['user_rank'],$users['user_name'],$Return_data);

//                $user_session = D("Sessions")->get_session($this->uid); //获取用户缓存数据
//                if($user_session){
//                    //有数据（判断是否过期）
//                    if($user_session['expiry']>time()){
//                        //在有效期
//                        D("Sessions")->update_session($user_session['sesskey'],$user_session['expiry']+$this->max_life_time,$Return_data);
//                    }else{
//                       //不在有效期，删除session_data  并更新session 表
//                        D("Sessions")->update_session($user_session['sesskey'],$user_session['expiry']+$this->max_life_time,$Return_data,$this->uid);
//                        D("Sessions")->del_session_data($user_session['sesskey']);
//                    }
//                }else{
//                    //无数据  新增
//                    D("Sessions")->add_session($this->uid,$this->max_life_time,$Return_data['email'],$users['user_rank'],$users['user_name'],$Return_data);
//                }


//                switch (local_date('d')){
//                    case 20:
//                        $this->check_use_bonus(463);
//                        break;
//                    case 21:
//                        $this->check_use_bonus(464);
//                        break;
//                    case 22:
//                        $this->check_use_bonus(466);
//                        break;
//                    case 23:
//                        $this->check_use_bonus(467);
//                        break;
//                    case 24:
//                        $this->check_use_bonus(465);
//                        break;
//                }



                returnApiSuccess($Return_data,"登录成功");
            }else{
                returnApiError("获取用户信息失败");
            }
        }else{
            returnApiError("用户id或者openid为空");
        }
    }
    /**
     * 上线领取红包
     * @param null $bonus_id
     * @return bool
     */
    public function check_use_bonus($bonus_id=null){
        if(empty($bonus_id)||!S("user_bonus_get_".$bonus_id)){
            return false;
        }
        $user_bonus_data = M("user_bonus")->
        where(array("bonus_type_id"=>$bonus_id,"user_id"=>$this->uid))->count();
        if($user_bonus_data==0){
            $bonus_data = M("bonus_type")->where(array("type_id"=>$bonus_id))->find();
            if($bonus_data['has_effective_days']==1 && $bonus_data['effective_days']>0){
                $end_time = time() + ($bonus_data['effective_days']-1)*24*3600;
                $end_date = date('Y-m-d',$end_time)." 23:59:59";
                $deadline = local_strtotime($end_date); //转换成GMT格林威治时间戳
            }else{
                $deadline = 0;
            }
            $bonus_id_f = M("user_bonus")->where(array("bonus_type_id"=>$bonus_id,"user_id"=>0))
                ->getField("bonus_id");
            if($bonus_id_f){
                $data['user_id'] = $this->uid;
                $data['get_time'] = gmtime();
                $data['deadline'] = $deadline;
                M("user_bonus")->where(array("bonus_id"=>$bonus_id_f))->save($data);
                S("user_bonus_get_".$bonus_id,"1",604800);
            }
        }
    }

    /**
     * 检查用户是否有领取新用户5元运费红包,如果未领取且没有过成交订单，自动领取一份
     */
    public function check_use_freight($bonus_id){

        $order_info = M("order_info")->where(array("user_id"=>$this->uid))->count();
        if($order_info==0){
            $user_bonus_data = M("user_bonus")->
            where(array("bonus_type_id"=>$bonus_id,"user_id"=>$this->uid))->count();

            if($user_bonus_data==0){
                $bonus_data = M("bonus_type")->where(array("type_id"=>$bonus_id))->find();

                if($bonus_data['has_effective_days']==1 && $bonus_data['effective_days']>0){
                    $end_time = time() + ($bonus_data['effective_days']-1)*24*3600;
                    $end_date = date('Y-m-d',$end_time)." 23:59:59";
                    $deadline = local_strtotime($end_date); //转换成GMT格林威治时间戳
                }else{
                    $deadline = 0;
                }

                $bonus_id_f = M("user_bonus")->where(array("bonus_type_id"=>$bonus_id,"user_id"=>0))
                    ->getField("bonus_id");

                if($bonus_id_f){
                    $data['user_id'] = $this->uid;
                    $data['get_time'] = gmtime();
                    $data['deadline'] = $deadline;
                    M("user_bonus")->where(array("bonus_id"=>$bonus_id_f))->save($data);
                }
            }
        }
    }
    /**
     * [HD专用接口] 用户登录
     * @param string phone 手机号码;
     * @param string smscode 短信验证码;
     */
    public function user_login_4hd() {
        if(!empty($this->uid)){
            $phone = I("post.phone");
            $smscode = I("post.smscode");   
            $IS_HD = I('post.IS_HD', 'Touch', 'trim');

            if( !empty($phone) && !empty($smscode) ) {
                $users = M("users")->field("password,paypwd",true)->where(array("user_id"=>$this->uid))->find();

                if($users){
                    $Return_data = $users;
                    $wechat_user = M("wechat_user")->field("openid,nickname,headimgurl")->where(array("ect_uid"=>$this->uid))->find();
                    if($wechat_user){
                        $Return_data['nickName']= $wechat_user['nickname'];
                        $Return_data['headImage']= $wechat_user['headimgurl'];
                        $Return_data['openId']= $this->open_id;
                    }
                    $Return_data['Uid']= $this->uid;
                    $Return_data['point']= $users['user_money'];
                    $Return_data['phone']= $users['mobile_phone'];

                    D("Users")->update_user_info($this->uid); //更新用户登录信息
                    D("Sessions")->update_session($this->session_id,$this->uid,$this->max_life_time,$users['email'],$users['user_rank'],$users['user_name'],$Return_data);

                    returnApiSuccess($Return_data,"登录成功");

                }else{
                    returnApiError("获取用户信息失败");
                }

            }else {
                returnApiError("请输入手机号与验证码");
            }

        }else{
            returnApiError("用户id为空");
        }
    }

    /**
     * ios微信登陆后，绑定手机号（手机登录后）
     */
    public function bind_phone_ios(){
        $phone = I("post.phone");
        if(empty($phone)){
            returnApiError('手机号为空');
        }
        $map = array("user_id"=>$this->uid);
        $userinfo = M('users')->where($map)->find();

        if(!empty($userinfo['mobile_phone']) && $userinfo['is_validated']==1){
            $res = array('has_bind'=>1);
            returnApiSuccess($res,'已绑定手机');
        }
        $data = array();
        $data['mobile_phone'] = $phone;
        $data['is_validated'] = 1;
        $res = M("users")->where($map)->save($data); //更换绑定手机和修改支付密码

        if($res!==false){
            D('Users')->write_user_action("buyer",$this->uid,"IOS绑定手机",$userinfo['mobile_phone'],$phone);	//写日志
            returnApiSuccess('','绑定手机成功');
        }else{
            returnApiError('绑定手机失败');
        }
    }

    /**
     *
     *发送验证码
     */
    public function get_verification_code(){
        $user_phone = I("post.phone");
        $is_voice = I("post.is_voice");
        if($user_phone){
            $ver_code = getSmsCode();
            $remark = array('is_voice'=>$is_voice);
            $send_result = A("Smsapi")->send_message_api("ver_code",$user_phone,D('Users')->get_user_nickname($this->uid),0,0,$ver_code,$this->uid,$remark);
            if($send_result){
                S($this->uid."_".$user_phone."_code",$ver_code,600);    //验证码保持600秒
                returnApiSuccess(null,'发送验证码成功');
            }else{
                returnApiError('发送验证码失败');
            }
        }else{
            returnApiError("请输入正确的手机号");
        }
    }

    /**
     * 判断此手机号是否已被其他账号绑定
     */
    public function check_moblie(){
        $phone = I("post.phone");
        $uid = I('post.uid');

        $map = array();
        $map['user_id'] = array('neq',$uid);
        $map['mobile_phone'] = $phone;
        $user_phone = D('users')->where($map)->getField('mobile_phone');

        if(!empty($user_phone)){
            returnApiError('此手机号已绑定其他账号');
        }else{
            returnApiSuccess('','手机号可绑定');
        }
    }

    /**
     *根据验证码 更换手机和支付密码
     */
    public function mobile_binding(){
        $input_code = I("post.smscode");
        $user_phone = I("post.phone");
        $pay_key = I("post.password");



        if(empty($pay_key)){
            returnApiError('支付密码不能为空');
        }
//
//        if(!is_numeric($pay_key)){
//            returnApiError('支付密码只能为6位纯数字');
//        }
//
//        if(strlen($pay_key) != 6){
//            returnApiError('支付密码只能为6位数字');
//        }

        $flag = $this->check_bind_phone($this->uid, $user_phone);

        if(!$flag){
            returnApiError('此手机号已绑定其他账号');
        }

        $sever_code = S($this->uid."_".$user_phone."_code");
        if(empty($sever_code)){
            returnApiError("验证码不正确");
        }else{
            if ($input_code==$sever_code){
//                $updata['paypwd'] = md5($pay_key . 'sdxPay');
                $updata['paypwd'] = strtolower($pay_key);
                $updata['mobile_phone'] = $user_phone;
                $updata['is_validated'] = 1;

                $user =  M("users")->field('user_id,user_money,mobile_phone')->where(array('user_id'=>$this->uid))->find();
                //根据手机号查询原会员信息
                $member = M('sg_member')->field('member_id,member_truename,member_email,available_predeposit,freeze_predeposit')->where(array('member_mobile_bind'=>1,'member_mobile'=>$user_phone))->find();
                if ($member) {
                    $updata['truename'] = $member['member_truename']; //原用户昵称
                    $updata['user_money'] = $user['user_money'] + $member['available_predeposit']; //用户余额=余额+原用户预存款
                    $updata['user_rank'] = 2;
                    $updata['rank_points'] = 10000; //会员积分升级为vip
                }
                //更新会员信息
                $updata_data = M("users")->where(array("user_id"=>$this->uid))->save($updata); //更换绑定手机和修改支付密码
                if($updata_data !== false){
                    if ($member) {
                        //删除原有会员记录
                        M('sg_member')->where(array('member_id'=>$member['member_id']))->delete();
                    }
                    //原会员余额，加入账户明细
                    if(floatval($member['available_predeposit'])>0){
                        $data['user_id'] = $this->uid;
                        $data['admin_user'] = '买家';
                        $data['amount'] = $member['available_predeposit'];
                        $data['add_time'] = gmtime();
                        $data['paid_time'] = gmtime();
                        $data['admin_note'] =  "老会员余额绑定";
                        $data['user_note'] = "老会员余额绑定";
                        $data['process_type'] = 0;
                        $data['payment'] = "余额支付";
                        $data['is_paid'] = 1;
                        M('user_account')->add($data);
                        D('payment')->insert_account_log($this->uid,$member['available_predeposit'],0,$updata['rank_points'],0,"老会员余额绑定");
                    }

                    S($this->uid."_".$user_phone."_code",null);     //验证成功，取消验证码
                    D('Users')->write_user_action("buyer",$this->uid,"绑定手机",$user['mobile_phone'],$user_phone);	//写日志
                    D('Users')->write_user_action("buyer",$this->uid,"修改支付密码","-","-");	//写日志
                    returnApiSuccess(null,"绑定手机号成功");
                }else{
                    returnApiError("绑定手机号失败");
                }
            }else{
                returnApiError("验证码不正确");
            }
        }
    }


    /**
     *根据验证码 更换手机和支付密码
     */
    public function user_mobile_binding(){
        $input_code = I("post.smscode");
        $user_phone = I("post.phone");

        if(empty($user_phone) || empty($input_code)){
            returnApiError('手机号和验证码不能为空');
        }
        $flag = $this->check_bind_phone($this->uid, $user_phone);

        if(!$flag){
            returnApiError('此手机号已绑定其他账号');
        }

        $sever_code = S($this->uid."_".$user_phone."_code");
        if(empty($sever_code)){
            returnApiError("验证码不正确");
        }else{
            if ($input_code==$sever_code){
                $updata['mobile_phone'] = $user_phone;
                $updata['is_validated'] = 1;

                $user =  M("users")->field('user_id,user_money,mobile_phone')->where(array('user_id'=>$this->uid))->find();
                //根据手机号查询原会员信息
                $member = M('sg_member')->field('member_id,member_truename,member_email,available_predeposit,freeze_predeposit')->where(array('member_mobile_bind'=>1,'member_mobile'=>$user_phone))->find();
                if ($member) {
                    $updata['truename'] = $member['member_truename']; //原用户昵称
                    $updata['user_money'] = $user['user_money'] + $member['available_predeposit']; //用户余额=余额+原用户预存款
                    $updata['user_rank'] = 2;
                    $updata['rank_points'] = 10000; //会员积分升级为vip
                }
                //更新会员信息
                $updata_data = M("users")->where(array("user_id"=>$this->uid))->save($updata); //更换绑定手机和修改支付密码
                if($updata_data !== false){
                    if ($member) {
                        //删除原有会员记录
                        M('sg_member')->where(array('member_id'=>$member['member_id']))->delete();
                    }
                    //原会员余额，加入账户明细
                    if(floatval($member['available_predeposit'])>0){
                        $data['user_id'] = $this->uid;
                        $data['admin_user'] = '买家';
                        $data['amount'] = $member['available_predeposit'];
                        $data['add_time'] = gmtime();
                        $data['paid_time'] = gmtime();
                        $data['admin_note'] =  "老会员余额绑定";
                        $data['user_note'] = "老会员余额绑定";
                        $data['process_type'] = 0;
                        $data['payment'] = "余额支付";
                        $data['is_paid'] = 1;
                        M('user_account')->add($data);
                        D('payment')->insert_account_log($this->uid,$member['available_predeposit'],0,$updata['rank_points'],0,"老会员余额绑定");
                    }

                    S($this->uid."_".$user_phone."_code",null);     //验证成功，取消验证码
                    D('Users')->write_user_action("buyer",$this->uid,"绑定手机",$user['mobile_phone'],$user_phone);	//写日志
                    returnApiSuccess(null,"绑定手机号成功");
                }else{
                    returnApiError("绑定手机号失败");
                }
            }else{
                returnApiError("验证码不正确");
            }
        }
    }


    public function check_bind_phone($uid,$phone){
        $map = array();
        $map['user_id'] = array('neq',$uid);
        $map['mobile_phone'] = $phone;
        $map['platform'] = 0;
        $user_phone = D('users')->where($map)->getField('mobile_phone');

        if(!empty($user_phone)){
            return false;
        }else{
            return true;
        }
    }
    /**
     *修改密码
     */
    public function  edit_password(){
        $old_password = I("post.oldpassword");  //当前密码
        $new_password = I("post.password", '', 'strtolower');     //新密码

        if(empty($new_password)){
            returnApiError('请输入新密码');
        }
//        $new_password =  md5($new_password . 'sdxPay');   //编译密码
//        $old_password =  md5($old_password . 'sdxPay');

        $current_passwors = M("users")->where(array("user_id"=>$this->uid))->getField("paypwd");
        //w_log("log","old:".$old_password."--".$current_passwors." sql：".M("users")->getlastsql());
        if(strtolower($current_passwors) == strtolower($old_password)){
            $updata = M("users")->where(array("user_id"=>$this->uid))->setField('paypwd',$new_password);
            if($updata){
                D('Users')->write_user_action("buyer",$this->uid,"修改支付密码","-","-");	//写日志
                returnApiSuccess(null,"修改密码成功");
            }else{
                returnApiError("修改密码操作失败，请重试");
            }
        }else{
            returnApiError("密码不正确");
        }
    }

    /**
     * 短信验证码修改密码
     */
    public function edit_password_by_mobile() {
        $ver_code = I ( 'post.ver_code' );
        $new_password = I ( "post.password" ); // 新密码
        $phone = I ( 'post.phone' );

        $flag = $this->check_bind_phone($this->uid, $phone);

        if(!$flag){
            returnApiError('此手机号已绑定其他账号');
        }

//        if(!is_numeric($new_password)){
//            returnApiError('密码必须为6位纯数字');
//        }
//
//        if(strlen($new_password) != 6){
//            returnApiError('密码必须为6位数数字');
//        }

        if (empty ( $ver_code )) {
            returnApiError ( '请输入验证码' );
        }
        $sever_code = S ( $this->uid . "_" . $phone . "_code" );
        if (empty ( $sever_code )) {
            returnApiError ( '验证码已过期,请重新获取验证码' );
        }

        if ($sever_code != $ver_code) {
            returnApiError ( '验证码不正确' );
        }

        if (empty ( $new_password )) {
            returnApiError ( '请输入新密码' );
        }

//        $new_password = md5 ( $new_password . 'sdxPay' );

        $map = array (
            "user_id" => $this->uid
        );
// 		$userinfo = M ( "users" )->field ( 'mobile_phone,is_validated' )->where ( $map )->find ();
// 		if (! empty ( $userinfo ) && $userinfo ['is_validated'] && $userinfo ['mobile_phone'] != trim ( $phone )) {
// 			returnApiError ( "当前手机号不是绑定的手机号" );
// 		}

        $savedata = array();
        $savedata['paypwd'] = $new_password;
        $savedata['mobile_phone'] = $phone;
        $savedata['is_validated'] = 1;
        $updata = M ( "users" )->where ( $map )->save($savedata);
        if ($updata !== false) {
            S ( $this->uid . "_" . $phone . "_code", null );
            D('Users')->write_user_action("buyer",$this->uid,"修改支付密码","-","-");	//写日志
            returnApiSuccess ( null, "修改密码成功" );
        } else {
            returnApiError ( "修改密码失败" );
        }
    }

    /*
     * 获取绑定手机号
     */
    public function get_bind_mobile(){
        $mobile = M("users")->where(array("user_id"=>$this->uid))->getField('mobile_phone');
        $result['mobile'] = $mobile;
        returnApiSuccess($result);
//     	if($mobile){
//     		returnApiSuccess($result);
//     	}else{
//     		returnApiError('没有绑定手机号');
//     	}
    }
    /**
     *我的收藏
     */
    public function my_collect(){
        $page_num = I("post.page");
        $page_num = intval($page_num);
        $wid = I('post.wid');
        if(empty($page_num) || $page_num==0){
            $page_num = 1;
        }
        $start = ($page_num-1)*C("page_size");

        $return_data = array();

        $collect_all = M("collect_goods")->where(array("user_id"=>$this->uid))->count();
        if($collect_all){
            $all_page = ceil($collect_all/C("page_size"));
            $return_data['sumcount'] = $collect_all;
            if($all_page == $page_num){
                //判断是否为最后一页
                $return_data['is_bottom'] = 1;
            }else{
                $return_data['is_bottom'] = 0;
            }

            $collect = M("collect_goods")->where(array("user_id"=>$this->uid))->limit($start,C("page_size"))->order("add_time desc")->select();
            $reduced_price_goods_total = 0;
            foreach ($collect as $key=>$value){
                $goods_mod = D('goods');
                $goods = $goods_mod->where(array("goods_id"=>$value['goods_id']))->field("goods_id,goods_sn,goods_thumb,goods_img,goods_name,goods_number,goods_brief,goods_desc,goods_weight,market_price,shop_price,promote_price,spec_value,spec_unit,is_presell,delivery_type,delivery_cycle,virtual_sales,min_buy_num,promote_start_date,promote_end_date,is_on_sale, promote_goods_number, promote_today_number, is_buynow")->find();

//				秒杀
                if($goods['is_buynow'] == 0){
                    $promoteService = new PromoteService();
                    $goods = $promoteService->formatPromoteData($goods);
                }
                else if ($goods['is_buynow'] == 1){
                    $buyNowService = new BuyNowGoodsService($this->uid, $wid);
                    $goods = $buyNowService->handleBuyNowGoodsData($goods);
                }

                $is_booking=D('Goods')->is_book_goods($goods['goods_id'],$this->uid,'');
                if($is_booking){
                    $collect[$key]['is_booking']='1';
                }else{
                    $collect[$key]['is_booking']='0';
                }
                $collect[$key]['goods_sn']  =$goods['goods_sn'];
                $collect[$key]['goods_img']  = img_init($goods['goods_img']);
                $collect[$key]['goods_name']  =$goods['goods_name'];
                $collect[$key]['goods_number']  =$goods['goods_number'];
                $collect[$key]['goods_brief']  =$goods['goods_brief'];
                $collect[$key]['goods_desc']  =$goods['goods_desc'];
                $collect[$key]['goods_weight']  =$goods['goods_weight'];
                $collect[$key]['shop_price']  =$goods['shop_price'];
                $collect[$key]['market_price']  = trim(D('goods')->get_vip_price_for_all($goods['goods_id'],1));    //市场价使用注册会员价


//				促销价
//				if($collect[$key]['promote_price']){
//					$collect[$key]['promote_start_date'] = date('Y-m-d', localtotime($goods['promote_start_date']));
//					$collect[$key]['promote_end_date'] = date('Y-m-d', localtotime($goods['promote_end_date']));
//					$promoteService = new PromoteService();
//					$collect[$key]['promote_message'] = $promoteService->getPromoteGoodsNumber($goods)->getNumberMessage();
//				}
//
//                $collect[$key]['promote_price']  = bargain_price($goods['promote_price'], $goods['promote_start_date'], $goods['promote_end_date']);

                //				秒杀
                if($goods['is_buynow'] == 0){
                    $collect[$key]['promote_message'] = isset($goods['promote_message']) ? $goods['promote_message'] : '';
                    $collect[$key]['promote_price'] = isset($goods['promote_price']) ? $goods['promote_price'] : '';
                    $collect[$key]['promote_start_date'] = isset($goods['promote_start_date']) ? $goods['promote_start_date'] : '';
                    $collect[$key]['promote_end_date'] = isset($goods['promote_end_date']) ? $goods['promote_end_date'] : '';
                }
                else if ($goods['is_buynow'] == 1){
                    $collect[$key]['buy_now_end_date'] = isset($goods['buy_now_end_date']) ? $goods['buy_now_end_date'] : '';
                    $collect[$key]['buy_now_start_date'] = isset($goods['buy_now_start_date']) ? $goods['buy_now_start_date'] : '';

                    $collect[$key]['buy_now_end_time'] = isset($goods['buy_now_end_time']) ? $goods['buy_now_end_time'] : '';
                    $collect[$key]['buy_now_start_time'] = isset($goods['buy_now_start_time']) ? $goods['buy_now_start_time'] : '';

                    $collect[$key]['buy_now_goods_number'] = isset($goods['buy_now_goods_number']) ? $goods['buy_now_goods_number'] : '';
                    $collect[$key]['buy_now_today_number'] = isset($goods['buy_now_today_number']) ? $goods['buy_now_today_number'] : '';

                    $collect[$key]['buy_now_price'] = isset($goods['buy_now_price']) ? $goods['buy_now_price'] : '';
                    $collect[$key]['buy_now_status'] = $goods['buy_now_status'];
                }


                $collect[$key]['vip_price'] = $goods_mod->get_vip_price($goods['goods_id'], $this->uid);
//                vip对比价
                $collect[$key]['true_vip_price'] = trim(D('goods')->get_vip_price_for_all($goods['goods_id']));
                $collect[$key]['spec_value']  =$goods['spec_value'];
                $collect[$key]['spec_unit']  =$goods['spec_unit'];
                $collect[$key]['virtual_sales']  =$goods['virtual_sales'];
                $collect[$key]['min_buy_num']  =$goods['min_buy_num'];
                $collect[$key]['is_presell']  =$goods['is_presell'];
                $collect[$key]['is_on_sale']  =$goods['is_on_sale'];
                $goods['is_presell']=(int)$goods['is_presell'];
                if($goods['is_presell']!=0){
                    //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
                    $goods['is_presell']=D('Goodsstorage')->check_whether_presell($goods['goods_id'],$wid,1);
                }
                $collect[$key]['is_presell']  =$goods['is_presell'];
                if($goods['is_presell']){
                    if($goods['delivery_type']==1){//分段发货
                        $Goodspreselltime=D('Goodspreselltime');
                        if($Goodspreselltime->check_shipping_goodspreselltime($goods['goods_id'])){//检查预售商品是否设置发货配送时间
                            $preselltimeres=$Goodspreselltime->check_shippingtime($goods['goods_id'],time());
                            if($preselltimeres){
                                $collect[$key]['preselltimeres']=array('delivery_time'=>$preselltimeres['delivery_time']);;
                            }else{
                                $collect[$key]['preselltimeres']=array('delivery_time'=>'');
                            }
                        }else{
                            $collect[$key]['preselltimeres']=array('delivery_time'=>'');
                        }
                    }elseif($goods['delivery_type']==2){//定时方式
                        if($goods['delivery_cycle']>=0){
                            $gmd=local_date('Y-m-d',gmtime());
                            $goods_presell_time = local_date('Y-m-d H:i:s', local_strtotime($gmd.' +'.$goods['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H')));
                            $collect[$key]['preselltimeres']=array('delivery_time'=>$goods_presell_time);
                        }else{
                            $collect[$key]['preselltimeres']=array('delivery_time'=>'');
                        }
                    }else{
                        $collect[$key]['preselltimeres']=array('delivery_time'=>'');
                    }
                }else{
                    $goodsstorage=D('Goodsstorage')->get_warehous_goods($wid,$goods['goods_id']);
                    if($goodsstorage){
                        $collect[$key]['goods_number']=$goodsstorage['practical_num'];
                    }else{
                        $collect[$key]['goods_number']=0;
                    }
                    $collect[$key]['preselltimeres']=array('delivery_time'=>'');
                }

                //获取初始加入购物车的价格
                $add_collect_price = S('goods_add_collect_price_'.$this->uid."_".$value['goods_id']);
                $collect[$key]['had_reduced_price'] = 0;
                $collect[$key]['reduced_price']=0;
                if(empty($add_collect_price)){
                    S('goods_add_collect_price_'.$this->uid."_".$value['goods_id'],$collect[$key]['vip_price']);
                }else{
                    $new_goods_price = D("goods")->get_final_price($value['goods_id'],1,'','',$this->uid);
                    if($add_collect_price-$new_goods_price>0){
                        $collect[$key]['had_reduced_price'] = 1;
                        $collect[$key]['reduced_price'] = round($add_collect_price-$new_goods_price,2);
                        $reduced_price_goods_total++;
                    }
                }

            }

            //处理金蝶商品库存
            /*$goodsStockQueryService = new GoodsStockQueryService();
            $collect = $goodsStockQueryService->getGoodsStockList($wid, $collect);*/

            $return_data['list'] = $collect;
            $return_data['reduced_price_goods_total_num'] = $reduced_price_goods_total;

            returnApiSuccess($return_data);

        }else{
            returnApiError("没有收藏数据");
        }
    }

    /**
     *取消收藏__硬删除
     */
    public function cancel_my_collect(){
        $rec_id = I("post.rec_id");
        $goods_id = I('post.goods_id');
        $wid=I('post.wid','intval');
        if(!empty($rec_id) || !empty($goods_id)){
            if(!empty($rec_id)){
                $where['rec_id'] = $rec_id;
            }
            if(!empty($goods_id)){
                $where['goods_id'] = $goods_id;
            }
            $where['user_id'] = $this->uid;
            $del_collect = M("collect_goods")->where($where)->delete();
            if($del_collect){
                S('goods_add_collect_price_'.$this->uid."_".$goods_id,null);
                //添加到用户行为
                $param = array('insertOne', $this->uid, $goods_id, I('wid') , 'uncollect', 1, 1);
                \Think\Hook::listen('receng', $param);

                returnApiSuccess(null,"取消收藏成功");
            }else{
                returnApiError("没有收藏此商品，取消收藏失败");
            }
        }else{
            returnApiError('参数错误');
        }
    }

    public function my_orders()
    {
        $page_num = I("post.page");
        $order_type = I("post.ordertype");
        if(empty($order_type) && $order_type!='0'){
            $order_type = "all";
        }
        switch ($order_type) {
            case '0'://待付款
            case '1'://待收货
            case '3'://已取消
                $return_data = $this->get_orders_by_status($this->uid,$order_type,$page_num);
            break;
            case '2'://待评价
                $return_data = $this->get_wait_comment_order($this->uid, $page_num);
            break;
            default:
                $return_data = $this->get_all_orders($this->uid, $page_num);
            break;
        }

        if ($return_data) {
            returnApiSuccess($return_data);
        } else {
            returnApiError("没有订单");
        }
    }

    private function get_wait_comment_order($uid,$page_num){
        $order_info = M("order_info");
        $sql = "select count(order_id) as nums from sdx_order_info where user_id=".$uid." and order_sn not in(select order_sn from sdx_comment) and shipping_status=".SS_RECEIVED." and order_status in(".OS_SPLITED.",".OS_CONFIRMED.")";
        $pending_comment = $order_info->query($sql);
        $pending_comment = current($pending_comment);
        $count = $pending_comment['nums'];
        if($count){
            $return_data['sumcount'] = $count;
            $pagearr = show_page($count, $page_num,5);
            if ($page_num == $pagearr['pagecount']) {
                //判断是否为最后一页
                $return_data['is_bottom'] = 1;
            } else {
                $return_data['is_bottom'] = 0;
            }

            $query_sql = "select DISTINCT(o.order_id),o.is_negative_to_sell,v.handle_type as overtime_handle,if(s.order_id,1,0) as is_free_single,o.user_id,o.order_sn,o.shipping_id,o.pay_id,
            o.order_amount,o.money_paid,o.surplus,o.order_status,o.shipping_status,o.pay_status,o.add_time,o.shipping_time,
            o.pay_time,o.confirm_time,o.is_presell,o.best_time,o.best_time_start,o.batch_no,c.comment_id 
from sdx_order_info o left join sdx_comment c on o.order_sn=c.order_sn LEFT JOIN sdx_order_info_free_single as s on o.order_id=s.order_id LEFT JOIN sdx_order_info_overtime as v on o.order_id=v.order_id where o.user_id=".$uid." and o.order_sn not in(select order_sn from sdx_comment) and o.shipping_status=".SS_RECEIVED." and o.order_status in(".OS_SPLITED.",".OS_CONFIRMED.") order by o.add_time desc limit ".$pagearr['firstpage'].",".$pagearr['pagesize'] ;
            $collect = $order_info->query($query_sql);

            foreach ($collect as $key => $value) {

                //是否超时免单 - 收货成功后若该订单准时送达/售后处理/未补偿，则不显示该标签
                if((($value['confirm_time']+3600*8) <= $value['best_time'] && $value['shipping_status']==2) || $value['overtime_handle']>1){
                    $collect[$key]['is_free_single'] = 0;
                }



                $order_goods = M("order_goods")->alias('og')
                    ->field("og.goods_id,og.goods_sn,og.goods_name,og.is_presell,og.buckle_inventory,g.goods_thumb as goods_img,g.goods_weight / g.goods_number as goods_weight,g.market_price,g.shop_price,g.promote_price")
                    ->join("left join ".C('DB_PREFIX').'goods g on og.goods_id=g.goods_id')
                    ->where(array("og.order_id" => $value['order_id']))
                    ->select();
                $is_presell = 0;
                foreach ($order_goods as $key_2 => $value_2) {
                    //                     $goods = M("goods")->where(array("goods_id" => $value_2['goods_id']))->field("goods_thumb,goods_weight,market_price,shop_price,promote_price")->find();
                    //                     $order_goods[$key_2]['goods_img'] = $goods['goods_thumb'];
                    //                     $order_goods[$key_2]['goods_weight'] = $goods['goods_weight'] . "/" . $goods['goods_number'];
                    //                     $order_goods[$key_2]['market_price'] = $goods['market_price'];
                    //                     $order_goods[$key_2]['shop_price'] = $goods['shop_price'];
                    //                     $order_goods[$key_2]['promote_price'] = $goods['promote_price'];
                    $order_goods[$key_2]['goods_img'] = img_init($value_2['goods_img']);
                    //如果订单中有一个商品是预售商品，则显示预售标识
                    if($value_2['is_presell']==1){
                        $is_presell = 1;
                    }

                    //负卖商品不标为预售
                    if($value['is_negative_to_sell']==1) {
                        $order_goods[$key_2]['is_presell'] = 0;
                    }
                }
                if($value['best_time_start']==0){
                    if($value['is_presell']==1){
                        $new_best_time = date("Y-m-d",$value['best_time'])." 20:30:00";
                        $collect[$key]['best_time'] = strtotime($new_best_time)-1;
                        $collect[$key]['best_time_start'] = strtotime(date("Y-m-d",$value['best_time'])." 10:00:00");

                    }else{
                        $collect[$key]['best_time_start'] = $value['best_time']-2*3600;
                    }
                }
                $collect[$key]['preselltimeres']=array('delivery_time'=>date("Y-m-d H:i:s",$collect[$key]['best_time_start']));

                $collect[$key]['goodslist'] = $order_goods;
                $collect[$key]['goodssum'] = count($order_goods);
                $collect[$key]['add_time'] = localtotime($value['add_time']);
                $collect[$key]['is_presell'] = $is_presell;
                $rest_pay_time = REST_PAY_TIME - (gmtime() - $value['add_time']);    //剩余支付时间（单位：秒）
                $collect[$key]['rest_pay_time'] = $rest_pay_time < 0 ? 0 : $rest_pay_time;

                //负卖商品不标为预售
                if($value['is_negative_to_sell']==1) {
                    $collect[$key]['is_presell'] = 0;
                }

                //                退款信息
                //                $collect[$key]['refund_detail'] = $this->get_refund_detail($collect[$key]);
                //                付款信息
                //                $collect[$key]['pay_detail'] = $this->get_pay_detail($collect[$key]);
                $collect[$key]['is_comment'] = is_null($value['comment_id'])?0:1;

                $code=md5($value['user_id'].'sdx@9999');

                $collect[$key]['comment_url'] = "index_c.php?index&oid=".$value['user_id']."&code=".$code."#!/reted?ordId=".$value['order_sn'];

            }
            //            dd($collect);
            $return_data['orderlist'] = $collect;

            return $return_data;
        }else{
            return false;
        }
    }

    private function get_orders_by_status($uid,$type,$page_num){
        $order_info = M("order_info");
        if($type==0){
            //未付款订单
            $map = array('o.user_id'=>$uid,'o.order_status'=>OS_UNCONFIRMED,'o.pay_status'=>PS_UNPAYED);
        }elseif($type==1){
            //待收货订单
            $map = array('o.user_id'=>$uid,'o.order_status'=>array('in',array(OS_CONFIRMED,OS_SPLITED)),'o.shipping_status'=>array('neq',SS_RECEIVED));
        }elseif($type==3){
            //已取消订单
            $map = array('o.user_id'=>$uid,'o.order_status'=>OS_CANCELED);
        }

        $count = $order_info->alias('o')->where($map)->count();

        if($count){
            $return_data['sumcount'] = $count;
            $pagearr = show_page($count, $page_num,5);
            if ($page_num == $pagearr['pagecount']) {
                //判断是否为最后一页
                $return_data['is_bottom'] = 1;
            } else {
                $return_data['is_bottom'] = 0;
            }
            $collect = $order_info
                ->alias('o')
                ->field("DISTINCT(o.order_id),o.is_negative_to_sell,v.handle_type as overtime_handle,if(s.order_id,1,0) as is_free_single,o.user_id,o.order_sn,o.shipping_id,o.pay_id,
            o.order_amount,o.money_paid,o.surplus,o.order_status,o.shipping_status,o.pay_status,o.add_time,o.shipping_time,
            o.pay_time,o.confirm_time,o.is_presell,o.best_time,o.best_time_start,o.batch_no,c.comment_id")
                ->join("left join sdx_comment c on o.order_sn=c.order_sn")
                ->join("left join sdx_order_info_free_single s on o.order_id=s.order_id")
                ->join("left join sdx_order_info_overtime v on o.order_id=v.order_id")
                ->where($map)
                ->limit($pagearr['firstpage'], $pagearr['pagesize'])
                ->order("add_time desc")
                ->select();

            foreach ($collect as $key => $value) {

                //是否超时免单 - 收货成功后若该订单准时送达，取消单/售后处理/未补偿 则不显示该标签/
                if((($value['confirm_time']+3600*8) <= $value['best_time'] && $value['shipping_status']==2) || $value['order_status']==2 || $value['overtime_handle']>1){
                    $collect[$key]['is_free_single'] = 0;
                }



                $order_goods = M("order_goods")->alias('og')
                    ->field("og.goods_id,og.goods_sn,og.goods_name,og.is_presell,og.buckle_inventory,g.goods_thumb as goods_img,g.goods_weight / g.goods_number as goods_weight,g.market_price,g.shop_price,g.promote_price")
                    ->join("left join ".C('DB_PREFIX').'goods g on og.goods_id=g.goods_id')
                    ->where(array("og.order_id" => $value['order_id']))
                    ->select();
                $is_presell = 0;
                foreach ($order_goods as $key_2 => $value_2) {
                    //                     $goods = M("goods")->where(array("goods_id" => $value_2['goods_id']))->field("goods_thumb,goods_weight,market_price,shop_price,promote_price")->find();
                    //                     $order_goods[$key_2]['goods_img'] = $goods['goods_thumb'];
                    //                     $order_goods[$key_2]['goods_weight'] = $goods['goods_weight'] . "/" . $goods['goods_number'];
                    //                     $order_goods[$key_2]['market_price'] = $goods['market_price'];
                    //                     $order_goods[$key_2]['shop_price'] = $goods['shop_price'];
                    //                     $order_goods[$key_2]['promote_price'] = $goods['promote_price'];
                    $order_goods[$key_2]['goods_img'] = img_init($value_2['goods_img']);
                    //如果订单中有一个商品是预售商品，则显示预售标识
                    if($value_2['is_presell']==1){
                        $is_presell = 1;
                    }

                    //负卖商品不标为预售
                    if($value['is_negative_to_sell']==1) {
                        $order_goods[$key_2]['is_presell'] = 0;
                    }
                }
                if($value['best_time_start']==0){
                    if($value['is_presell']==1){
                        $new_best_time = date("Y-m-d",$value['best_time'])." 20:30:00";
                        $collect[$key]['best_time'] = strtotime($new_best_time)-1;
                        $collect[$key]['best_time_start'] = strtotime(date("Y-m-d",$value['best_time'])." 10:00:00");

                    }else{
                        $collect[$key]['best_time_start'] = $value['best_time']-2*3600;
                    }
                }
                $collect[$key]['preselltimeres']=array('delivery_time'=>date("Y-m-d H:i:s",$collect[$key]['best_time_start']));

                $collect[$key]['goodslist'] = $order_goods;
                $collect[$key]['goodssum'] = count($order_goods);
                $collect[$key]['add_time'] = localtotime($value['add_time']);
                $collect[$key]['is_presell'] = $is_presell;
                $rest_pay_time = REST_PAY_TIME - (gmtime() - $value['add_time']);    //剩余支付时间（单位：秒）
                $collect[$key]['rest_pay_time'] = $rest_pay_time < 0 ? 0 : $rest_pay_time;

                //负卖商品不标为预售
                if($value['is_negative_to_sell']==1) {
                    $collect[$key]['is_presell'] = 0;
                }

                //                退款信息
                //                $collect[$key]['refund_detail'] = $this->get_refund_detail($collect[$key]);
                //                付款信息
                //                $collect[$key]['pay_detail'] = $this->get_pay_detail($collect[$key]);
                $collect[$key]['is_comment'] = is_null($value['comment_id'])?0:1;

                $code=md5($value['user_id'].'sdx@9999');

                $collect[$key]['comment_url'] = "index_c.php?index&oid=".$value['user_id']."&code=".$code."#!/reted?ordId=".$value['order_sn'];

            }
            //            dd($collect);
            $return_data['orderlist'] = $collect;

            return $return_data;

        }else{
            return false;
        }

    }
    /**
     * @param $uid
     * @param $page_num
     * @return array|bool
     */
    private function get_all_orders($uid,$page_num){
        $where = array();
        $where['o.user_id'] = $uid;
        $where['o.order_status'] = array('neq',3);
        $return_data = array();
        $order_info = M("order_info o");
        $collect_all = $order_info->join("left join sdx_comment c on o.order_sn=c.order_sn")->field("DISTINCT(o.order_id)")->where($where)->count();
        if ($collect_all) {
            $return_data['sumcount'] = $collect_all;
            $pagearr = show_page($collect_all, $page_num,5);
            if ($page_num == $pagearr['pagecount']) {
                //判断是否为最后一页
                $return_data['is_bottom'] = 1;
            } else {
                $return_data['is_bottom'] = 0;
            }

            $collect = $order_info
                ->field("DISTINCT(o.order_id),o.is_negative_to_sell,v.handle_type as overtime_handle,if(s.order_id,1,0) as is_free_single,o.user_id,o.order_sn,o.shipping_id,o.pay_id,
            o.order_amount,o.money_paid,o.surplus,o.order_status,o.shipping_status,o.pay_status,o.add_time,o.shipping_time,
            o.pay_time,o.confirm_time,o.is_presell,o.best_time,o.best_time_start,o.batch_no,c.comment_id")
                ->join("left join sdx_comment c on o.order_sn=c.order_sn")
                ->join("left join sdx_order_info_free_single s on o.order_id=s.order_id")
                ->join("left join sdx_order_info_overtime v on o.order_id=v.order_id")
                ->where($where)
                ->limit($pagearr['firstpage'], $pagearr['pagesize'])
                ->order("add_time desc")
                ->select();

            foreach ($collect as $key => $value) {

                //是否超时免单 - 收货成功后若该订单准时送达，取消单/售后处理/未补偿 则不显示该标签
                if((($value['confirm_time']+3600*8) <= $value['best_time'] && $value['shipping_status']==2) || $value['order_status']==2 || $value['overtime_handle']>1){
                    $collect[$key]['is_free_single'] = 0;
                }


                
                $order_goods = M("order_goods")->alias('og')
                    ->field("og.goods_id,og.goods_sn,og.goods_name,og.is_presell,og.buckle_inventory,g.goods_thumb as goods_img,g.goods_weight / g.goods_number as goods_weight,g.market_price,g.shop_price,g.promote_price")
                    ->join("left join ".C('DB_PREFIX').'goods g on og.goods_id=g.goods_id')
                    ->where(array("og.order_id" => $value['order_id']))
                    ->select();
                $is_presell = 0;
                foreach ($order_goods as $key_2 => $value_2) {
                    //                     $goods = M("goods")->where(array("goods_id" => $value_2['goods_id']))->field("goods_thumb,goods_weight,market_price,shop_price,promote_price")->find();
                    //                     $order_goods[$key_2]['goods_img'] = $goods['goods_thumb'];
                    //                     $order_goods[$key_2]['goods_weight'] = $goods['goods_weight'] . "/" . $goods['goods_number'];
                    //                     $order_goods[$key_2]['market_price'] = $goods['market_price'];
                    //                     $order_goods[$key_2]['shop_price'] = $goods['shop_price'];
                    //                     $order_goods[$key_2]['promote_price'] = $goods['promote_price'];
                    $order_goods[$key_2]['goods_img'] = img_init($value_2['goods_img']);
                    //如果订单中有一个商品是预售商品，则显示预售标识
                    if($value_2['is_presell']==1){
                        $is_presell = 1;
                    }

                    //负卖商品不标为预售
                    if($value['is_negative_to_sell']==1) {
                        $order_goods[$key_2]['is_presell'] = 0;
                    }
                }
                if($value['best_time_start']==0){
                    if($value['is_presell']==1){
                        $new_best_time = date("Y-m-d",$value['best_time'])." 20:30:00";
                        $collect[$key]['best_time'] = strtotime($new_best_time)-1;
                        $collect[$key]['best_time_start'] = strtotime(date("Y-m-d",$value['best_time'])." 10:00:00");

                    }else{
                        $collect[$key]['best_time_start'] = $value['best_time']-2*3600;
                    }
                }
                $collect[$key]['preselltimeres']=array('delivery_time'=>date("Y-m-d H:i:s",$collect[$key]['best_time_start']));

                $collect[$key]['goodslist'] = $order_goods;
                $collect[$key]['goodssum'] = count($order_goods);
                $collect[$key]['add_time'] = localtotime($value['add_time']);
                $collect[$key]['is_presell'] = $is_presell;
                $rest_pay_time = REST_PAY_TIME - (gmtime() - $value['add_time']);    //剩余支付时间（单位：秒）
                $collect[$key]['rest_pay_time'] = $rest_pay_time < 0 ? 0 : $rest_pay_time;

                //负卖商品不标为预售
                if($value['is_negative_to_sell']==1) {
                    $collect[$key]['is_presell'] = 0;
                }

                //                退款信息
                //                $collect[$key]['refund_detail'] = $this->get_refund_detail($collect[$key]);
                //                付款信息
                //                $collect[$key]['pay_detail'] = $this->get_pay_detail($collect[$key]);
                $collect[$key]['is_comment'] = is_null($value['comment_id'])?0:1;

                $code=md5($value['user_id'].'sdx@9999');

                $collect[$key]['comment_url'] = "index_c.php?index&oid=".$value['user_id']."&code=".$code."#!/reted?ordId=".$value['order_sn'];

            }
            //            dd($collect);
            $return_data['orderlist'] = $collect;

            return $return_data;
        } else {
            return false;
        }
    }
    /**
     *获取订单
     */
    public function my_orders_old()
    {
        $page_num = I("post.page");
        $order_type = I("post.ordertype");
        if ($order_type != 'all') {
            switch ($order_type) {
                case 0:
                    $where['o.pay_status'] = 0;   //待付款
                    break;
                case 1:
                    $where['o.shipping_status'] = 1;   //已发货
                    break;
                case 2:
                    $where['o.shipping_status'] = 2;   //已完成
                    break;
            }
        }

        $where['o.user_id'] = $this->uid;
        $where['o.order_status'] = array('neq',3);
        $return_data = array();
        $order_info = M("order_info o");
        $collect_all = $order_info->join("left join sdx_comment c on o.order_sn=c.order_sn")->field("DISTINCT(o.order_id)")->where($where)->count();
        if ($collect_all) {
            $return_data['sumcount'] = $collect_all;
            $pagearr = show_page($collect_all, $page_num,5);
            if ($page_num == $pagearr['pagecount']) {
                //判断是否为最后一页
                $return_data['is_bottom'] = 1;
            } else {
                $return_data['is_bottom'] = 0;
            }

            $collect = $order_info->field("DISTINCT(o.order_id),o.user_id,o.order_sn,o.shipping_id,o.pay_id,
            o.order_amount,o.money_paid,o.surplus,o.order_status,o.shipping_status,o.pay_status,o.add_time,o.shipping_time,
            o.pay_time,o.confirm_time,o.is_presell,o.best_time,o.best_time_start,o.batch_no,c.comment_id")->join("left join sdx_comment c on o.order_sn=c.order_sn")->where($where)->limit($pagearr['firstpage'], $pagearr['pagesize'])->order("add_time desc")->select();

            foreach ($collect as $key => $value) {
                $order_goods = M("order_goods")->alias('og')
                    ->field("og.goods_id,og.goods_sn,og.goods_name,og.is_presell,og.buckle_inventory,g.goods_thumb as goods_img,g.goods_weight / g.goods_number as goods_weight,g.market_price,g.shop_price,g.promote_price")
                    ->join("left join ".C('DB_PREFIX').'goods g on og.goods_id=g.goods_id')
                    ->where(array("og.order_id" => $value['order_id']))
                    ->select();
                $is_presell = 0;
                foreach ($order_goods as $key_2 => $value_2) {
//                     $goods = M("goods")->where(array("goods_id" => $value_2['goods_id']))->field("goods_thumb,goods_weight,market_price,shop_price,promote_price")->find();
//                     $order_goods[$key_2]['goods_img'] = $goods['goods_thumb'];
//                     $order_goods[$key_2]['goods_weight'] = $goods['goods_weight'] . "/" . $goods['goods_number'];
//                     $order_goods[$key_2]['market_price'] = $goods['market_price'];
//                     $order_goods[$key_2]['shop_price'] = $goods['shop_price'];
//                     $order_goods[$key_2]['promote_price'] = $goods['promote_price'];
                    $order_goods[$key_2]['goods_img'] = img_init($value_2['goods_img']);
                    //如果订单中有一个商品是预售商品，则显示预售标识
                    if($value_2['is_presell']==1){
                        $is_presell = 1;
                    }
                }
                if($value['best_time_start']==0){
                    if($value['is_presell']==1){
                        $new_best_time = date("Y-m-d",$value['best_time'])." 20:30:00";
                        $collect[$key]['best_time'] = strtotime($new_best_time)-1;
                        $collect[$key]['best_time_start'] = strtotime(date("Y-m-d",$value['best_time'])." 10:00:00");

                    }else{
                        $collect[$key]['best_time_start'] = $value['best_time']-2*3600;
                    }
                }
                $collect[$key]['preselltimeres']=array('delivery_time'=>date("Y-m-d H:i:s",$collect[$key]['best_time_start']));

                $collect[$key]['goodslist'] = $order_goods;
                $collect[$key]['goodssum'] = count($order_goods);
                $collect[$key]['add_time'] = localtotime($value['add_time']);
                $collect[$key]['is_presell'] = $is_presell;
                $rest_pay_time = REST_PAY_TIME - (gmtime() - $value['add_time']);    //剩余支付时间（单位：秒）
                $collect[$key]['rest_pay_time'] = $rest_pay_time < 0 ? 0 : $rest_pay_time;

//                退款信息
//                $collect[$key]['refund_detail'] = $this->get_refund_detail($collect[$key]);
//                付款信息
//                $collect[$key]['pay_detail'] = $this->get_pay_detail($collect[$key]);
                $collect[$key]['is_comment'] = is_null($value['comment_id'])?0:1;

                $code=md5($value['user_id'].'sdx@9999');

                $collect[$key]['comment_url'] = "index_c.php?index&oid=".$value['user_id']."&code=".$code."#!/reted?ordId=".$value['order_sn'];

            }
//            dd($collect);
            $return_data['orderlist'] = $collect;

            returnApiSuccess($return_data);
        } else {
            returnApiError("没有订单");
        }
    }

    /**
     * 获取用户订单商品
     * @param $uid
     * @param $wid
     * @param int $rec_ids
     * @param int $flow_type
     * @return mixed
     */
    public function get_cart_goods_by_uid($wid,$order_id){
        $map = array();

        $user_rank = M('user_rank')->where(array('rank_id'=>2))->find();


        $map['c.order_id'] = $order_id;
        $map['mp.user_rank'] = 2;
        $cart = D('order_goods');
        $cart_goods = $cart->alias("c")
            ->field("c.*,1 as is_check,IFNULL(mp.user_price,g.shop_price*(".$user_rank['discount']."/100)) as vip_price,g.shop_price,IF(c.parent_id, c.parent_id, c.goods_id) AS pid,g.cat_id,g.brand_id,goods_weight,g.spec_value,g.spec_unit,g.is_presell,g.delivery_type,g.delivery_cycle,g.min_buy_num,g.goods_number as goods_stock,g.goods_thumb,g.goods_img,g.goods_brief,g.is_on_sale,g.promote_price,g.promote_end_date,g.promote_start_date,g.practical_num,g.is_auto_morrow_presell")
            ->join("left join ".C('DB_PREFIX')."goods_wid_".$wid." g on c.goods_id=g.goods_id")
            ->join("left join ".C('DB_PREFIX')."member_price mp on g.goods_id = mp.goods_id")
            ->where($map)
            ->order("c.giving asc")
            ->select();

        return $cart_goods;
    }

    /**
     * 处理订单状态
     * @author Min
     * @param $order
     * @return array
     */
    protected function handel_order_status($order)
    {
        $status = 0;
        $remark = '';

        //待支付
        if ($order['order_status'] == 0 && $order['pay_status'] == 0) {
            $status = 0;
            $remark = '请在15分钟内完成支付，超时订单将自动取消';
        }

        //订单已取消
        if ($order['order_status'] == 2) {
            $status = 1;
            if ($order['pay_status'] == 0) {
                if ($order['to_buyer'] == '支付超时自动取消') {
                    $remark = '您的订单超时未支付已自动取消，如果需要请点击再次购买';
                } else {
                    $remark = '您的订单已取消成功';
                }

            } else {
                $remark = '订单已取消成功，您的退款金额将在1-3个工作日内退回，感谢您使用食得鲜';
            }
        }

        /**
         * 线上状态
         */
        if ($order['shipping_id'] == 3) {
            //未配货
            if ($order['shipping_status'] == 0  && in_array($order['pay_status'], array(2,3))) {
                $status = 2;
                $remark = '订单已支付，等待配货中';
            }

            //配货中
            if ($order['shipping_status'] == 3) {
                $status = 3;
                $remark = '订单准备中';
            }

            //配货完成
            if ($order['shipping_status'] == 5 && $order['quality_id'] == 0 && $order['outgo'] == 0 ) {
                $status = 4;
                $remark = '订单已完成配货，等待质检';
            }

            //商品质量已确认
            if ($order['shipping_status'] == 5 && $order['quality_id'] != 0 && $order['outgo'] == 0 ) {
                $status = 5;
                $remark = '订单内商品已完成质检，等待出仓';
            }

            //订单已出仓
            if ($order['shipping_status'] == 5 && $order['quality_id'] != 0 && $order['outgo'] == 1 ) {
                $status = 6;
                $remark = '订单已离开仓库，等待配送';
            }

            //配送中
            if ($order['shipping_status'] == 1) {
                $status = 7;
                $remark = '配送员 : '.$order['shipping_exman_name'].'  '.$order['shipping_exman_mobile'];
            }

            //已收货，配送完成
            if ($order['shipping_status'] == 2) {
                $status = 8;
                $remark = $order['comment_id'] ? '感谢您使用食得鲜' : '感谢您使用食得鲜，请对配送员及订单商品进行评价';
            }
        }

        /**
         * 线下门店专题
         */
        if($order['shipping_id'] == 2) {
            //已付款，待打印小票
            if ($order['shipping_status'] == 0  && in_array($order['pay_status'], array(2,3))) {
                $status = 2;
                $remark = '离场时请前往收银台核销二维码打印小票';
            }

            //已付款，订单完成
            if ($order['shipping_status'] == 2) {
                $status = 3;
                $remark = $order['comment_id'] ? '感谢您使用食得鲜' : '感谢您使用食得鲜，请对门店服务及商品进行评价';
            }
        }

        $data = array(
            'status' => $status,
            'remark' => $remark
        );

        return $data;

    }

    /**
     *获取订单详情
     */
    public function myorder_details_new(){
        $order_id = I("post.order_id");
        if(!empty($order_id)){

            $order_details = M("order_info")
                ->alias("o")
                ->join("left join sdx_comment as c on o.order_sn=c.order_sn")
                ->join("left join sdx_order_info_free_single s on o.order_id=s.order_id")
                ->field("o.is_negative_to_sell,o.shipping_exman_mobile,o.shipping_exman_name,o.outgo,o.quality_id,o.to_buyer,if(s.order_id,1,0) as is_free_single,o.bonus_freight_id,o.user_id,o.order_id,o.order_sn,o.shipping_id,o.pay_id,
            o.order_amount,o.money_paid,o.surplus,o.order_status,o.shipping_status,o.pay_status,o.add_time,o.shipping_time,
            o.pay_time,o.confirm_time,o.consignee,o.country,o.province,o.city,o.district,o.address,o.address_name,o.mobile,o.goods_amount,o.shipping_fee,o.insure_fee,
            o.pay_fee,o.pack_fee,o.card_fee,o.wp_userid,o.best_time,o.best_time_start,o.bonus_id,o.bonus,o.integral_money,o.integral,o.discount,o.is_presell,o.postscript,o.batch_no,o.wid,o.cancel_type,c.comment_id")
                ->where(array("o.order_id"=>$order_id))
                ->order("o.add_time desc")
                ->find();

            //处理订单状态
            $order_status = $this->handel_order_status($order_details);
            $order_details['order_status_new'] = $order_status['status'];
            $order_details['order_remark'] = $order_status['remark'];

            //是否超时免单，确认收货、取消单不显示
            if($order_details['shipping_status']==2 || $order_details['order_status']==2){
                $order_details['is_free_single'] = 0;
            }

            //负卖商品不标为预售
            if($order_details['is_negative_to_sell']==1) {
                $order_details['is_presell'] = 0;
            }

            $order_details['is_comment'] = is_null($order_details['comment_id'])?0:1;
            $code=md5($order_details['user_id'].'sdx@9999');
            $order_details['comment_url'] = "index_c.php?index&oid=".$order_details['user_id']."&code=".$code."#!/reted?ordId=".$order_details['order_sn'];


            //获取订单详情
            //$order_goods = $this->get_cart_goods_by_uid($order_details['wid'], $order_details['order_id']);
            //M("order_goods")->field("*")->where(array("order_id"=>$order_id))->order("giving asc")->select();
            $order_goods = M("order_goods")->field("rec_id,discount_price,goods_id,goods_sn,goods_name,goods_number,goods_price,market_price,is_presell,buckle_inventory,is_quota,is_gift,giving,bonus_price")->where(array("order_id"=>$order_id))->order("giving asc")->select();

            $goods_total_price = 0;
            
            foreach ($order_goods as $key_2=>$value_2){
                //折扣价
                $order_goods[$key_2]['goods_discount_price']=0;
                if($value_2['discount_price']>0){
                    $order_goods[$key_2]['goods_discount_price']=$value_2['discount_price']-$value_2['goods_price'];
                }


                //获取订单里面商品的内容
                $goods = M("goods")->where(array("goods_id"=>$value_2['goods_id']))->field("is_negative_to_sell,goods_id,goods_thumb,goods_weight,spec_value,spec_unit,market_price,shop_price,promote_price,is_presell,delivery_type,delivery_cycle,goods_type,goods_number as goods_stock")->find();

                if(!empty($goods['goods_type'])){
                    $attribute = M("attribute")->where(array("cat_id"=>$goods['goods_type']))->field("attr_name,attr_id")->find();
                    $order_goods[$key_2]['goods_attr'] = $attribute['attr_name'];  //cat_id
                    $order_goods[$key_2]['goods_attr_id'] = $attribute['attr_id'];  //cat_id
                }else{
                    $order_goods[$key_2]['goods_attr'] = null;  //cat_id
                    $order_goods[$key_2]['goods_attr_id'] = null;  //cat_id
                }

                //标识订单详情里面商品是否是预售商品。1-预售，0-现售
                if($value_2['is_presell']==1 && $value_2['buckle_inventory']==1){
                    $order_goods[$key_2]['is_presell']=0;
                }elseif($value_2['is_presell']==1){
                    $order_goods[$key_2]['is_presell']=1;
                }else{
                    $order_goods[$key_2]['is_presell']=0;
                }

                //负卖商品不标为预售
                if($order_details['is_negative_to_sell']==1) {
                    $order_goods[$key_2]['is_presell'] = 0;
                }

                $order_goods[$key_2]['goods_img'] = img_init($goods['goods_thumb']);
                $order_goods[$key_2]['goods_weight'] = $goods['goods_weight'];
                if($goods['spec_value']){
                    $order_goods[$key_2]['spec_value'] =  $goods['spec_value'];
                    $order_goods[$key_2]['spec_unit'] =  $goods['spec_unit'];
                }elseif($goods['goods_weight']){
                    $order_goods[$key_2]['spec_value'] =  $goods['goods_weight']*1000;
                    $order_goods[$key_2]['spec_unit'] =  "g";
                }
                if($value_2['is_quota']>0){
                    $order_goods[$key_2]['act_type'] = "is_quota";
                    $order_goods[$key_2]['act_id'] = $value_2['is_quota'];
                }else{
                    $order_goods[$key_2]['act_type'] = 0;
                    $order_goods[$key_2]['act_id'] = 0;
                }
                $order_goods[$key_2]['market_price'] = $goods['market_price'];
                $order_goods[$key_2]['shop_price'] = $goods['shop_price'];
                $order_goods[$key_2]['promote_price'] = 0;
                $order_goods[$key_2]['goods_total_price'] = round(($value_2['goods_price']+$value_2['bonus_price'])*$value_2['goods_number'],2);
//                 $goods['is_presell']=(int)$goods['is_presell'];
//                 if($goods['is_presell']!=0){
//                     //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
//                     $goods['is_presell']=D('Goodsstorage')->check_whether_presell($goods['goods_id'],$order_details['wid']);
//                 }
//                 $order_goods[$key_2]['is_presell']  =$goods['is_presell'];
                if($order_goods[$key_2]['is_presell']==1){
                    $order_goods[$key_2]['goods_stock'] = $goods['goods_stock'];
                    //                    dd(111);
                    if($goods['delivery_type']==1){//分段发货
                        $Goodspreselltime=D('Goodspreselltime');
                        if($Goodspreselltime->check_shipping_goodspreselltime($goods['goods_id'])){//检查预售商品是否设置发货配送时间
                            $preselltimeres=$Goodspreselltime->check_shippingtime($goods['goods_id'],time());
                            if($preselltimeres){
                                $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>$preselltimeres['delivery_time']);;
                            }else{
                                $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>'');
                            }
                        }else{
                            $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>'');
                        }
                    }elseif($goods['delivery_type']==2){//定时方式
                        if($goods['delivery_cycle']>=0){
                            $gmd=local_date('Y-m-d',gmtime());
                            $goods_presell_time = local_date('Y-m-d H:i:s', local_strtotime($gmd.' +'.$goods['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H')));
                            $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>$goods_presell_time);
                        }else{
                            $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>'');
                        }
                    }else{
                        $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>'');
                    }
                }else{
                    $goodsstorage=D('Goodsstorage')->get_warehous_goods($order_details['wid'],$goods['goods_id']);
                    if($goodsstorage){
                        $order_goods[$key_2]['goods_stock']=$goodsstorage['practical_num'];
                    }else{
                        $order_goods[$key_2]['goods_stock']=0;
                    }

                    $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>'');
                }
                $goods_total_price+=$order_goods[$key_2]['goods_total_price'];

                //减去退款后的数量
                    $refund_number=$this->get_refund_goods_number($order_id,$value_2['goods_id'],$value_2['rec_id']);
                    
                    $order_goods[$key_2]['pick_number']=$value_2['goods_number']-$refund_number;
                    

            }


            $order_details['goods_amount'] = $goods_total_price;
            $order_details['goodslist'] = $order_goods;
            $order_details['goodssum'] = count($order_goods);
            $order_details['add_time'] = localtotime($order_details['add_time']);
            $warehouse_info = D('Warehouse')->get_warehouse_address($order_details['wid']);
            $order_details['pickedup_address'] = $warehouse_info['addr'];
            if($order_details['wp_userid']){
                $order_details['phone'] = M('warehouse_personnel')->where(array('uid'=>$order_details['wp_userid']))->getField('phone');
            }else{
                $order_details['phone'] = '';
            }

            $order_details['pay_detail'] = $this->get_pay_detail($order_details);
            $order_details['refund_detail'] = $this->get_refund_detail($order_details,$order_id);
            //            自提时间
            $order_details['expected_pickup_time'] = D("Orderinfo")->get_expected_pickup_time($order_details);

            //临时修改，自提注意提示
            if($order_details['shipping_id']==2){
//                $start_msg = "请于";
//                $end_msg = "前往门店领取，若超时未自提系统将自动为您取消订单。";
//                $order_details['expected_pickup_time'] = $start_msg.$order_details['expected_pickup_time'].$end_msg;

                $order_details['expected_pickup_time'] = "为保障您购买的生鲜的品质，自提订单完成支付后大圣仅帮您保管一个小时，超时将为您取消订单并自动退款，红包不予退回";
            }

            $rest_pay_time = REST_PAY_TIME - (localtotime() - $order_details['add_time']);	//剩余支付时间（单位：秒）
            $order_details['rest_pay_time'] = $rest_pay_time<0?0:$rest_pay_time;

            $user_rank=M("users")->where(array('user_id'=>$order_details['user_id']))->getField("user_rank");
            $user_rank==2?$is_vip=1:$is_vip=0;
            $favourable_list = D('NewCart')->favourable_list_flow($order_details['user_id'],$order_details['wid']);
            $order_goods=D("NewCart")->convert_cart_goods($order_goods, $favourable_list,true);
            $res=D("NewCart")->get_cart_total($order_goods,$favourable_list);


            $order_details['is_vip'] = $is_vip;
            $order_details['vip_only_need'] = $res['total']['total_vip_price'];  //订单价格+运费
            $order_details['order_amount'] = $order_details['order_amount'];  //订单价格+运费
            $order_details['vip_reduce'] = $res['total']['derivative_price'];

            //订单对应楼小二信息
            $louxiaoer = D('LouxiaoerOrder')->findOrderLouxiaoerInfoByOrderId($order_id);
            $order_details['wechat_name'] = 'shidexian020'; //楼小二微信号
            $order_details['wechat_barcode_img'] = $louxiaoer['wechat_barcode_img']; //楼小二微信二维码图片
            $order_details['louxiaoer_name'] = $louxiaoer['name']; //楼小二名字
            $order_details['louxiaoer_phone'] = $louxiaoer['phone']; //楼小二手机号

            $order_details['receipt_code_new'] = D("users")->get_order_receipt_code($order_id);

            if($order_details['order_status']!=2&&$order_details['shipping_status']!=2){
                if($order_details['pay_status']==2||$order_details['pay_status']==3){
                    $order_details['receipt_code'] = D("users")->get_order_receipt_code($order_id);
                }
            }

            //订单商品分组
            if($order_details['pay_status']==0){
                $order_details['goods_list_group'] = D('NewCart')->get_cart_goods_list_group($order_details['goodslist'],false);
            }else{
                $order_pay_detail = $order_details['pay_detail']['detail'];
                $order_details['goods_list_group'] = D('NewCart')->get_order_goods_list_group($order_pay_detail['goodslist']);
            }

            $order_details['can_cancel'] = $this->check_order_cancel_status($order_id);


            //发票详情
            if($order_details['order_status'] != 2 && $order_details['pay_status'] > 1){
                $invoice_info = D('OrderInvoice')->get_invoice_info($order_id);
            }
            $order_details['invoice_info'] = $invoice_info ? $invoice_info : '';

            $order_details['wid_name']=M("warehouse")->where(array("id"=>$order_details['wid']))->getField("name");
            if(gmtime()<1514188800&&gmtime()>1514102400&&
                $order_details['pay_time']<1514188800&&$order_details['pay_time']>1514102400){
                $order_details['is_action'] = 1;
            }else{
                $order_details['is_action'] = 0;
            }


            //发票内容
            $order_details['invoice_content'] = D('OrderInvoice')->get_invoice_content();

            //写入行为日志
            $user_behavior = new UserBehavior();
            $user_behavior->add_user_behavior_order($order_details['user_id'], $order_id, 4);

            returnApiSuccess($order_details);
        }else{
            returnApiError("oder_id不能为空");
        }
    }
    

    public function get_order_receipt_code(){
        $order_id = I("post.order_id");
        if(!empty($order_id)) {
            $order_details['receipt_code'] = D("users")->get_order_receipt_code($order_id);
            returnApiSuccess($order_details);
        }else{
            returnApiError("oder_id不能为空");
        }
    }

    public function get_refund_goods_number($order_id,$goods_id,$order_goods_id=0){
        $refund_log = M("refund_detail");
        $where['order_id']=$order_id;
        $where['goods_id']=$goods_id;
        if(!empty($order_goods_id)){
            $where['order_goods_id']=$order_goods_id;
        }
        $refund_number = $refund_log->where($where)->sum("refund_number");
        
        return $refund_number;
    }

    public function check_order_cancel_status($order_id){
        $can_cancel=1;
        $map = array('order_id'=>$order_id,'action_note'=>array('like','%配货中%'));
        $count = D('order_action')->where($map)->count();
        if($count>0){
            $can_cancel=0;
        }
        return $can_cancel;
    }

    /**
     *获取订单详情
     */
    public function myorder_details(){
        $order_id = I("post.order_id");
        if(!empty($order_id)){

            $order_details = M("order_info")->field("bonus_freight_id,order_id,order_sn,shipping_id,pay_id,
            order_amount,money_paid,surplus,order_status,shipping_status,pay_status,add_time,shipping_time,
            pay_time,confirm_time,consignee,country,province,city,district,address,mobile,goods_amount,shipping_fee,insure_fee,
            pay_fee,pack_fee,card_fee,wp_userid,best_time,best_time_start,bonus_id,bonus,integral_money,integral,discount,is_presell,postscript,batch_no,wid,cancel_type")->where(array("order_id"=>$order_id))->order("add_time desc")->find();

            //获取订单详情
            $order_goods = M("order_goods")->field("goods_id,goods_sn,goods_name,goods_number,goods_price,market_price,is_presell,buckle_inventory,is_quota,is_gift,giving,bonus_price")->where(array("order_id"=>$order_id))->order("giving asc")->select();

            foreach ($order_goods as $key_2=>$value_2){
                //获取订单里面商品的内容
                $goods = M("goods")->where(array("goods_id"=>$value_2['goods_id']))->field("goods_id,goods_thumb,goods_weight,spec_value,spec_unit,market_price,shop_price,promote_price,is_presell,delivery_type,delivery_cycle,goods_type,goods_number as goods_stock")->find();

                if(!empty($goods['goods_type'])){
                    $attribute = M("attribute")->where(array("cat_id"=>$goods['goods_type']))->field("attr_name as name,attr_id")->find();
                    $order_goods[$key_2]['goods_attr'] = $attribute['name'];  //cat_id
                    $order_goods[$key_2]['goods_attr_id'] = $attribute['attr_id'];  //cat_id
                }else{
                    $order_goods[$key_2]['goods_attr'] = null;  //cat_id
                    $order_goods[$key_2]['goods_attr_id'] = null;  //cat_id
                }

                //标识订单详情里面商品是否是预售商品。1-预售，0-现售
                if($value_2['is_presell']==1 && $value_2['buckle_inventory']==1){
                    $order_goods[$key_2]['is_presell']=0;
                }elseif($value_2['is_presell']==1){
                    $order_goods[$key_2]['is_presell']=1;
                }else{
                    $order_goods[$key_2]['is_presell']=0;
                }

                $order_goods[$key_2]['goods_img'] = img_init($goods['goods_thumb']);
                $order_goods[$key_2]['goods_weight'] = $goods['goods_weight'];
                if($goods['spec_value']){
                    $order_goods[$key_2]['spec_value'] =  $goods['spec_value'];
                    $order_goods[$key_2]['spec_unit'] =  $goods['spec_unit'];
                }elseif($goods['goods_weight']){
                    $order_goods[$key_2]['spec_value'] =  $goods['goods_weight']*1000;
                    $order_goods[$key_2]['spec_unit'] =  "g";
                }
                if($value_2['is_quota']>0){
                    $order_goods[$key_2]['act_type'] = "is_quota";
                    $order_goods[$key_2]['act_id'] = $value_2['is_quota'];
                }else{
                    $order_goods[$key_2]['act_type'] = 0;
                    $order_goods[$key_2]['act_id'] = 0;
                }
                $order_goods[$key_2]['market_price'] = $goods['market_price'];
                $order_goods[$key_2]['shop_price'] = $goods['shop_price'];
                $order_goods[$key_2]['promote_price'] = $goods['promote_price'];
                $order_goods[$key_2]['goods_total_price'] = $value_2['goods_price']*$value_2['goods_number'];
                $goods['is_presell']=(int)$goods['is_presell'];
                if($goods['is_presell']!=0){
                    //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
                    $goods['is_presell']=D('Goodsstorage')->check_whether_presell($goods['goods_id'],$order_details['wid'],1);
                }
                $order_goods[$key_2]['is_presell']  =$goods['is_presell'];
                if($goods['is_presell']==1){
                    $order_goods[$key_2]['goods_stock'] = $goods['goods_stock'];
//                    dd(111);
                    if($goods['delivery_type']==1){//分段发货
                        $Goodspreselltime=D('Goodspreselltime');
                        if($Goodspreselltime->check_shipping_goodspreselltime($goods['goods_id'])){//检查预售商品是否设置发货配送时间
                            $preselltimeres=$Goodspreselltime->check_shippingtime($goods['goods_id'],time());
                            if($preselltimeres){
                                $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>$preselltimeres['delivery_time']);;
                            }else{
                                $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>'');
                            }
                        }else{
                            $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>'');
                        }
                    }elseif($goods['delivery_type']==2){//定时方式
                        if($goods['delivery_cycle']>=0){
                            $gmd=local_date('Y-m-d',gmtime());
                            $goods_presell_time = local_date('Y-m-d H:i:s', local_strtotime($gmd.' +'.$goods['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H')));
                            $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>$goods_presell_time);
                        }else{
                            $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>'');
                        }
                    }else{
                        $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>'');
                    }
                }else{
                    $goodsstorage=D('Goodsstorage')->get_warehous_goods($order_details['wid'],$goods['goods_id']);
                    if($goodsstorage){
                        $order_goods[$key_2]['goods_stock']=$goodsstorage['practical_num'];
                    }else{
                        $order_goods[$key_2]['goods_stock']=0;
                    }

                    $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>'');
                }

            }
            $order_details['goodslist'] = $order_goods;
            $order_details['goodssum'] = count($order_goods);
            $order_details['add_time'] = localtotime($order_details['add_time']);
            $order_details['pickedup_address'] = C('DEFAULT_PICKEDUP_ADDRESS');
            if($order_details['wp_userid']){
                $order_details['phone'] = M('warehouse_personnel')->where(array('uid'=>$order_details['wp_userid']))->getField('phone');
            }else{
                $order_details['phone'] = '';
            }

            $order_details['pay_detail'] = $this->get_pay_detail($order_details);
            $order_details['refund_detail'] = $this->get_refund_detail($order_details);
//            自提时间
            $order_details['expected_pickup_time'] = D("Orderinfo")->get_expected_pickup_time($order_details);
            $rest_pay_time = REST_PAY_TIME - (localtotime() - $order_details['add_time']);	//剩余支付时间（单位：秒）
            $order_details['rest_pay_time'] = $rest_pay_time<0?0:$rest_pay_time;

            returnApiSuccess($order_details);
        }else{
            returnApiError("oder_id不能为空");
        }
    }

    /*
     * 订单支付详情
     */
    private function get_pay_detail($order_details){
        $result = array();
        if($order_details['batch_no']>0){
            $orders = D('order_info')->where(array('batch_no'=>$order_details['batch_no']))->select();
            if(!empty($orders)){
                if(count($orders)==1){
                    $order_details['have_relate_orders'] = 0;
                    $order_details['relate_orders'] = array();
                    $result['totalprice'] = $order_details['order_amount']+$order_details['money_paid']+$order_details['surplus'];
                    $result['detail'] = $order_details;
                }elseif(count($orders)>1){
                    $goods_list = array();
                    $order_details['goods_amount']= 0;
                    $order_details['money_paid']= 0;
                    $order_details['surplus']= 0;
                    $order_details['order_amount']= 0;
                    foreach ($orders as $o_key=>$order){
                        //获取订单详情
                        $order_goods = M("order_goods")->field("goods_id,goods_sn,goods_name,goods_number,goods_price,market_price,is_presell,buckle_inventory,is_quota,is_gift,giving,act_id,bonus_price")->where(array("order_id"=>$order['order_id']))->select();
                        $order_goods_amount = 0;
                        foreach ($order_goods as $key_2=>$value_2){
                            //获取订单里面商品的内容
                            $goods = M("goods")->field("goods_id,goods_thumb,goods_weight,spec_value,spec_unit,market_price,shop_price,promote_price,is_presell,delivery_type,delivery_cycle,goods_type,goods_number as goods_stock")->where(array("goods_id"=>$value_2['goods_id']))->find();

                            if(!empty($goods['goods_type'])){
                                $attribute = M("attribute")->where(array("cat_id"=>$goods['goods_type']))->field("attr_name as name,attr_id")->find();
                                $order_goods[$key_2]['goods_attr'] = $attribute['name'];  //cat_id
                                $order_goods[$key_2]['goods_attr_id'] = $attribute['attr_id'];  //cat_id
                            }else{
                                $order_goods[$key_2]['goods_attr'] = null;  //cat_id
                                $order_goods[$key_2]['goods_attr_id'] = null;  //cat_id
                            }

                            $order_goods[$key_2]['goods_img'] = img_init($goods['goods_thumb']);
                            $order_goods[$key_2]['goods_weight'] = $goods['goods_weight'];
                            if($goods['spec_value']){
                                $order_goods[$key_2]['spec_value'] =  $goods['spec_value'];
                                $order_goods[$key_2]['spec_unit'] =  $goods['spec_unit'];
                            }elseif($goods['goods_weight']){
                                $order_goods[$key_2]['spec_value'] =  $goods['goods_weight']*1000;
                                $order_goods[$key_2]['spec_unit'] =  "g";
                            }

                            if($value_2['is_quota']>0){
                                $order_goods[$key_2]['act_type'] = "is_quota";
                                $order_goods[$key_2]['act_id'] = $value_2['is_quota'];
                            }else{
                                $order_goods[$key_2]['act_type'] = 0;
                                $order_goods[$key_2]['act_id'] = 0;
                            }

                            $order_goods[$key_2]['market_price'] = $goods['market_price'];
                            $order_goods[$key_2]['shop_price'] = $goods['shop_price'];
                            $order_goods[$key_2]['promote_price'] = $goods['promote_price'];
                            $order_goods[$key_2]['goods_total_price'] = round(($value_2['goods_price']+$value_2['bonus_price'])*$value_2['goods_number'],2);
                            $goods['is_presell']=(int)$goods['is_presell'];
                            if($goods['is_presell']!=0){
                                //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
                                $goods['is_presell']=D('Goodsstorage')->check_whether_presell($goods['goods_id'],$order['wid'],1);
                            }
                            $order_goods[$key_2]['is_presell']  =$goods['is_presell'];
                            if($goods['is_presell']==1){
                                $order_goods[$key_2]['goods_stock'] = $goods['goods_stock'];
                                if($goods['delivery_type']==1){//分段发货
                                    $Goodspreselltime=D('Goodspreselltime');
                                    if($Goodspreselltime->check_shipping_goodspreselltime($goods['goods_id'])){//检查预售商品是否设置发货配送时间
                                        $preselltimeres=$Goodspreselltime->check_shippingtime($goods['goods_id'],time());
                                        if($preselltimeres){
                                            $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>$preselltimeres['delivery_time']);;
                                        }else{
                                            $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>'');
                                        }
                                    }else{
                                        $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>'');
                                    }
                                }elseif($goods['delivery_type']==2){//定时方式
                                    if($goods['delivery_cycle']>=0){
                                        $gmd=local_date('Y-m-d',gmtime());
                                        $goods_presell_time = local_date('Y-m-d H:i:s', local_strtotime($gmd.' +'.$goods['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H')));
                                        $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>$goods_presell_time);
                                    }else{
                                        $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>'');
                                    }
                                }else{
                                    $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>'');
                                }
                            }else{
                                $goodsstorage=D('Goodsstorage')->get_warehous_goods($order['wid'],$goods['goods_id']);
                                if($goodsstorage){
                                    $order_goods[$key_2]['goods_stock']=$goodsstorage['practical_num'];
                                }else{
                                    $order_goods[$key_2]['goods_stock']=0;
                                }
                                $order_goods[$key_2]['preselltimeres']=array('delivery_time'=>'');
                            }
                            $order_goods[$key_2]['order_id'] = $order['order_id'];
                            $order_goods[$key_2]['order_sn'] = $order['order_sn'];
                            $order_goods[$key_2]['best_time_start'] = $order['best_time_start'];
                            $order_goods[$key_2]['order_status'] = $order['order_status'];
                            $order_goods[$key_2]['shipping_status'] = $order['shipping_status'];
                            $order_goods[$key_2]['pay_status'] = $order['pay_status'];
                            $goods_list[] = $order_goods[$key_2];
                            $order_goods_amount += $order_goods[$key_2]['goods_total_price'];
                        }
                        $order['goods_amount'] = $order_goods_amount;
                        $order_details['goods_amount']+=$order['goods_amount'];
                        $order_details['money_paid']+=$order['money_paid'];
                        $order_details['surplus']+=$order['surplus'];
                        $order_details['order_amount']+=$order['order_amount'];
                        $order_details['goodssum']+=$order['goodssum'];

                        //判断是否是当前的订单
                        $orders[$o_key]['is_current'] = $order['order_id']==$order_details['order_id']?1:0;

                        //订单支付金额
                        $orders[$o_key]['pay_total_price'] = $order['order_amount']+$order['money_paid']+$order['surplus'];

                        $order_details['discount'] = $order['discount'];
                        $order_details['insure_fee'] = $order['insure_fee'];
                        $order_details['integral'] = $order['integral'];
                        $order_details['integral_money'] = $order['integral_money'];
                        $order_details['pack_fee'] = $order['pack_fee'];
                    }

                    $order_price = $order_details['money_paid']+$order_details['surplus']+$order_details['order_amount']+$order_details['bonus']+$order_details['discount']+$order_details['integral_money'];

                    if($order_price>=$order_details['goods_amount']){
                        if($order_details['pay_id']==1 || $order_details['pay_id']==2){
                            $order_details['money_paid'] = $order_details['money_paid'] - $order_details['bonus'] - $order_details['discount']-$order_details['integral_money'];
                        }elseif($order_details['pay_id']==3){
                            $order_details['surplus'] = $order_details['surplus'] - $order_details['bonus'] - $order_details['discount']-$order_details['integral_money'];
                        }
                    }

                    $order_details['have_relate_orders'] = 1;
                    $order_details['relate_orders'] = $orders;
                    $order_details['goodslist'] = $goods_list;

                    $result['totalprice'] = $order_details['order_amount']+$order_details['money_paid']+$order_details['surplus'];

                    $result['detail'] = $order_details;
                }
            }
        }else{
            $order_details['have_relate_orders'] = 0;
            $order_details['relate_orders'] = array();
            $result['totalprice'] = $order_details['order_amount']+$order_details['money_paid']+$order_details['surplus'];
            $result['detail'] = $order_details;
        }

        return $result;
    }

    /**
     * 订单退款明细
     * @param $order_details
     * @return mixed
     */
    private function get_refund_detail($order_details,$order_id_rui){
//        dd($order_details);
        if($order_details['batch_no']>0){
            $map = array('batch_no'=>$order_details['batch_no']);
            $order_ids = M("order_info")->where($map)->getField("order_id",true);
            $where = array('order_id'=>array("in",$order_ids));
        }else{
            $where = array(
                'order_id'=>$order_details['order_id'],
            );
//             dd($where);
        }

        $refund_log = M("refund_log");
        $refund_log_list = $refund_log->where($where)->select();

        $reund_totalprice = 0;
        foreach ($refund_log_list as $key=>$log){
            $reund_totalprice+=$log['refund_amount'];
            $refund_log_list[$key]['opt_time'] = local_date("Y-m-d H:i:s",$log['opt_time']);
            $map = array('log_id'=>$log['log_id']);
            $refund_detail_list = M('refund_detail')->field("log_id,order_id,goods_id,goods_name,opt_time,opt_note,refund_amount")->where($map)->select();
            $refund_log_list[$key]['list'] = $refund_detail_list;
        }
        $is_refund_freight = M("order_info")->where(array("order_id"=>$order_id_rui))->field("is_refund_freight,shipping_fee")->find();
        if($is_refund_freight['is_refund_freight']>0){
            $result['refund_freight'] = $is_refund_freight['shipping_fee'];
        }

        $result['reund_totalprice'] = $reund_totalprice;
        $result['reund_list'] = $refund_log_list;

        return $result;
    }


    public function get_start_interface(){
        $uid = $this->uid;

        $is_have = S('start_interface_'.$uid);
        $start_inter = array();
        $pic_url = array(
            'http://w.shidexian.com/Public/images1/slide1.jpg',
            'http://w.shidexian.com/Public/images1/slide2.jpg',
            'http://w.shidexian.com/Public/images1/slide3.jpg',
            'http://w.shidexian.com/Public/images1/slide4.jpg'
        );
        if(!empty($is_have)){
            $start_inter['show'] = 0;
            $start_inter['pic_count'] = 4;
            $start_inter['pic_url'] = $pic_url;
        }else{
            $start_inter['show'] = 1;
            $start_inter['pic_count'] = 4;
            $start_inter['pic_url'] = $pic_url;
            S('start_interface_'.$uid,"1",3*24*3600);
        }
        $result['start_inter'] = $start_inter;
        returnApiSuccess($result);
    }
    /**
     *我的消息列表
     */
    public function my_feedback_list(){
        $page_num = I("post.page");
        if(empty($page_num)){
            $page_num = 1;
        }
        $feedback_data = D("Feedback")->get_feedback_list($this->uid,$page_num);
        if($feedback_data){
            returnApiSuccess($feedback_data);
        }else{
            returnApiError('暂无消息');
        }
    }

    /**
     *新加消息
     */
    public function my_feedback_add(){
        $title = I("post.msg_title");
        $content = I("post.msg_content");
        $type = I("post.msg_type");
        if(empty($title)||empty($content)||empty($type)){
            returnApiError('type/title/content is null');
        }else{
            $add_return = D("Feedback")->add_feedback($type,$title,$content,$this->uid);
            if($add_return){
                returnApiSuccess(null,'新增消息成功');
            }else{
                returnApiError('新增消息成功');
            }
        }
    }

    /**
     *删除消息
     */
    public function my_feedback_del(){
        $msg_id = I("post.msg_id");
        if(empty($msg_id)){
            returnApiError('消息不存在或已删除');
        }else{
            $del_return = D('Feedback')->del_feedback($this->uid,$msg_id);
            if($del_return){
                returnApiSuccess(null,'删除成功');
            }else{
                returnApiError('删除失败');
            }
        }
    }

    /**
     *我的红包
     */
    public function my_bonus(){
        $page_num = I("post.page");
        if(empty($page_num)){
            $page_num = 1;
        }
        $show_all = I('post.show_all',1);
        $bonus_data = D("Userbonus")->get_user_bonus($this->uid,$page_num,$show_all);
        //添加行为
        $user_bevavior = new UserBehavior();
        $user_bevavior->add_browse(I('uid'), 19);

        if($bonus_data){
            returnApiSuccess($bonus_data);
        }else{
            returnApiError('没有红包');
        }
    }

    /**
     *添加红包
     */
    public function my_bonus_add(){
        $bonus_sn = I("post.bonus_sn");     //获取红包编号
        if (!is_numeric($bonus_sn)||strlen($bonus_sn)>15){
            returnApiError('红包长度不正确，卡券，请到：我的->我要充值->卡卷充值  中使用卡券');
        }else{
            //获取红包详情
            $bonus_type_id = D('Userbonus')->where(array('bonus_sn'=>$bonus_sn))->getField('bonus_type_id');
            if(empty($bonus_type_id)){
                returnApiError('添加红包失败');
            }
            $bonus_detail = M('bonus_type')->where(array('type_id'=>$bonus_type_id))->find();
            //判断红包是否满足等级要求
            $res = $this->check_bouns_rank($this->uid,$bonus_detail);
            if(!$res){
                returnApiError("当前用户等级不符合领取红包要求");
            }
            $bonus_data = D('Userbonus')->new_user_bonus($this->uid,$bonus_sn);

            if($bonus_data){
                returnApiSuccess($bonus_data,'success');
            }else{
                returnApiError('添加红包失败');
            }
        }
    }

    /**
     *账户明细
     */
    public function my_recharge_detail(){
        $page_num = I("post.page");
        if(empty($page_num)){
            $page_num = 1;
        }

        $log_all = M('account_log')->where(array("user_id"=>$this->uid))->count();
        if($log_all) {
            $return_data['sumcount'] = $log_all;
            $all_page = ceil($log_all / C("page_size"));
            $start = ($page_num-1) *C("page_size");
            $return_data['sumcount'] = $log_all;
            if ($all_page == $page_num) {
                //判断是否为最后一页
                $return_data['is_bottom'] = 1;
            } else {
                $return_data['is_bottom'] = 0;
            }
            $feedback_data = M('account_log')->where(array("user_id"=>$this->uid))->limit($start,C("page_size"))->order("change_time desc")->select();
            foreach ($feedback_data as $key=>$val){
                $feedback_data[$key]['change_time'] = localtotime($val['change_time']);
            }
            $return_data['list'] = $feedback_data;
            returnApiSuccess($return_data,'recharge list success');
        }else{
            returnApiError('暂无账户明细');
        }
    }


    /**
     *新加充值卡劵
     */
    public function new_card_coupons(){
        $card_sn = I("post.card_sn");       //充值卡号
        if (!is_numeric($card_sn)){
            returnApiError('卡号长度不正确，如是红包，请到：我的->设置->我的红包  中添加红包');
        }else{
            //判断用户是否绑定手机号码

            $userModel = D("Users");
            $user_phone = $userModel->get_user_phone($this->uid);
            if(!$user_phone){
                returnApiError("未绑定手机");
            }

            $data['user_id'] = $this->uid;
            $data['use_time'] = gmtime();
            $data['state'] = 2;

            $where['card_sn'] = $card_sn;
            $where['user_id'] = 0;
            $where['use_time'] = 0;
            $where['state'] = 1;

            $cardModel = M('card_coupons');

            $card_info = $cardModel->where(array("card_sn"=>$card_sn))->find();
            if(!$card_info){
                returnApiError("无此券号，请在微信号联系客服或楼管家 如是红包，请到：我的->设置->我的红包  中添加红包");
            }
//            检查权限和数量
            $coupons_auth = $this->is_coupons_auth($card_sn);
            if($coupons_auth !== true){
                returnApiError($coupons_auth);
            }


            if($card_info['user_id']!=0||$card_info['use_time']!=0){
                //w_log("log","已被使用:".$card_sn."-".$this->uid);
                returnApiError("该卡券已被使用");
            }
            if($card_info['state']!=1){
                //w_log("log","卡劵未激活:".$card_sn."-".$this->uid);
                returnApiError("该卡券处于禁用状态，请在微信号联系客服或楼管家");
            }

//            修改卡劵状态
            $use_card = $cardModel->where($where)->save($data);

            if($use_card){
                //充值卡使用成功,写入充值记录

                $card_id = M("card_coupons")->where(array('card_sn'=>$card_sn))->getField('card_class');
                $card_price= M("card_coupons_class")->field("price,name,up_vip,is_gift")->where(array('id'=>$card_id))->find();
                //修改账户余额

                $data_account['user_id'] = $this->uid;
                $data_account['admin_user'] = '';
                $data_account['amount'] = $card_price['price'];
                $data_account['add_time'] = gmtime();
                $data_account['paid_time'] = gmtime();
                $data_account['user_note'] = 'user';
                $data_account['admin_user'] = '买家';
                $data_account['is_paid'] = 1;
                if($card_price['is_gift']==1){
                    $data_account['admin_note'] =  "使用赠送卡劵:[ ".$card_price['name']." ]</br>卡号:[ ".$card_sn." ]";
                    $data_account['process_type'] = 7;
                    $data_account['payment'] = '充值卡劵 [ 赠送 ]';
                }else{
                    $data_account['admin_note'] =  "使用卡劵:[ ".$card_price['name']." ]</br>卡号:[ ".$card_sn." ]";
                    $data_account['process_type'] = 0;
                    $data_account['payment'] = '充值卡劵';
                }
                $res = M("user_account")->add($data_account);
                if(!$res){
                    //w_log("log","新加卡劵出错:".$card_sn."-".$this->uid);
                    returnApiError("新加卡劵出错:user_account");
                }
                $account_log = array(
                    'user_id' => $this->uid,
                    'user_money' => $card_price['price'],
                    'frozen_money' => 0,
                    'rank_points' => 0,
                    'pay_points' => 0,
                    'change_time' => gmtime(),
                    'change_desc' => "使用卡券 [ ".$card_sn." ]",
                    'change_type' => 0
                );
                if($card_price['is_gift']==1){
                    $account_log['change_type'] = 8;
                    $account_log['change_desc'] = "使用赠送卡券 [ ".$card_sn." ]";
                }
                $res = M("account_log")->add($account_log);
                if(!$res){
                    //w_log("log","新加卡劵出错account_log:".$card_sn."-".$this->uid);
                    returnApiError("新加卡劵出错:account_log");
                }
                $res = M("users")->where('user_id='.$this->uid)->setInc('user_money',$card_price['price']);
                if(!$res){
                    //w_log("log","新加卡劵出错users:".$card_sn."-".$this->uid);
                    returnApiError("新加卡劵出错:users");
                }
                D('Users')->write_user_action("buyer",$this->uid,"卡劵充值","-",$card_price['name'].":".$card_sn);	//写日志
                //returnApiError(null,'ok');
                if($card_price['up_vip']>0){
                    //使用此卡劵可升级为VIP用户
                    M("users")->where(array("user_id"=>$this->uid))->setField("user_rank",2);
                    D('Users')->write_user_action("buyer",$this->uid,"卡劵充值 [ 变VIP ]","-",$card_price['name'].":".$card_sn);	//写日志
                }

                returnApiSuccess(null,'ok');

            }else{
                //使用失败
                //w_log("log","使用卡券失败:".$card_sn."-".$this->uid);
                returnApiError('使用卡券失败');
            }
        }
    }

    /**
     * 检查卡劵权限
     * Created by Jerry
     * @param $card_sn
     * @return bool|string
     */
    public function is_coupons_auth($card_sn)
    {
        $userModel = D('users');
        $cardModel = M('card_coupons');

        $where['card_sn'] = $card_sn;
        $where['user_id'] = 0;
        $where['use_time'] = 0;
        $where['state'] = 1;

        $userRank = $userModel->get_user_rank($this->uid);
        $cardData = $cardModel->where($where)->find();
//            获取类型卡劵
        $classWhere = array(
            'id'    =>  $cardData['card_class'],
        );
//            检查此类型卡劵数量限制
        $cardWhere = array(
            'card_class'    =>  $cardData['card_class'],
            'user_id'       =>  $this->uid,
        );
        $cardCount = $cardModel->where($cardWhere)->count();

        $coupon_class = M('card_coupons_class')->where($classWhere)->find();


        if($coupon_class['is_vip'] !=0 && ($coupon_class['is_vip'] != $userRank['user_rank'])){
            return '对不起，您的会员等级不符';
        }

//            检查数量限制
        if($coupon_class['astrict'] > 0 and ($cardCount >= $coupon_class['astrict'])){
            return '该批次卡劵充值已达上限';
        }

        return true;
    }

    /**
     *获取我的充值卡券
     */
    public function get_my_coupons(){

        //$my_card= $this->model->table('card_coupons')->where('user_id ='.session('user_id'))->order('use_time desc')->select();

        $my_card=M('card_coupons')->where('user_id ='.$this->uid)->order('use_time desc')->select();

        foreach ($my_card as $key=>$value){

            $card_price_class= M('card_coupons_class')->field('price,name')->where('id ='.$value['card_class'])->find();

            //dump($card_price_class);
            //dump($value['card_class']);
            $my_card[$key]['price']= $card_price_class['price'];
            $my_card[$key]['name']= $card_price_class['name'];
            $my_card[$key]['time']= date("Y-m-d H:i:s",localtotime($value['use_time']));
        }
        $data['data']=$my_card;
        returnApiSuccess($data);
    }


    /**
     *根据GPS坐标获取周边地址大厦
     */
    public function get_near_address(){
        $key_array = array(
            "RFDBZ-BJL3F-463JB-J5VHW-Z2QDV-GQFV6",      //50W次KEY
            "RROBZ-OUFKP-RSKDT-LPEF7-GPWMK-IKFZF",
            "DECBZ-36DRG-CQQQY-IIRZV-LADUF-EGBNG",
            "4GJBZ-MWRRX-JPV4H-TOTTS-4RLVS-RABIX",
            "NQ5BZ-HEE3X-D3D4L-7NLSA-G4GPT-QXFHZ",
            "NYLBZ-NLS3X-VRZ4F-ZK7XB-46UT7-KOBNC",
            "I6MBZ-YYPWU-U66V3-B2J2P-WGCNO-4WBZ5",
            "HG3BZ-UOAHR-QLMWE-WJRVM-6Z337-OCBZN",
            "EAFBZ-772RX-ADQ4F-Z3SVS-BCUZ2-A6BLU",
            "VYIBZ-E56RP-I44DP-VJUD3-MSZ5Q-IJFQF",
            "26MBZ-FN3RP-U2DDA-VF6XQ-CZA5S-ZXFNZ",
        );

        $lat = I("post.lat");
        $lng = I("post.lng");
        $page = I("post.page");
        if(empty($page)||$page<=0){
            $page = 1;
        }

        foreach ($key_array as $key=>$value){
            //$url = "http://apis.map.qq.com/ws/place/v1/search?boundary=region('广州',0,".$lat.",".$lng.")&page_size=10&keyword=大厦&key=".$value;
            $url = "http://apis.map.qq.com/ws/place/v1/search?boundary=nearby(".$lat.",".$lng.",1000)&page_size=10&keyword=大厦&key=".$value."&page_index=".$page;
            $html = file_get_contents($url);


            $data = json_decode($html,true);

            //dump($url);
            if($data['status']==0){

                if($page>10){
                    $data['is_bottom'] = 1;
                }else{
                    $data['is_bottom'] = 0;
                }
                returnApiSuccess($data,'near address name');



                break;
            }
        }
        returnApiError('获取地址信息失败，请重试');
    }

    /**
     * 获取所有的坐标信息
     */
    public function get_all_gps(){
        $Model=new Model();
        $sql="
		SELECT rc.longitude,rc.latitude,rc.rid,r.wdtype,start_price FROM  
			sdx_warehouse_deliver_region_coordinates AS rc,
			sdx_warehouse_deliver_region AS r
		WHERE 
			rc.rid = r.id
			AND r.status = 1
		";
        $coordinates=$Model->query($sql);

        //$coordinates = M("warehouse_deliver_region_coordinates")->select();

        if(!$coordinates){
            returnApiError("数据错误");
        }

        $distribution_mode=S('distribution_mode_data');
        if(!$distribution_mode){
            $distribution_mode = M("distribution_mode")->where(array("state"=>0))->select();
            if($distribution_mode){
                S('distribution_mode_data',$distribution_mode);
            }
        }
        foreach ($distribution_mode as $value){
            $map_color[$value['id']] = "#7F".substr($value['color'],1);
        }



        $map_data = array();
        foreach ($coordinates as $key=>$value){
            $map_data[$value['rid']]['gps'][]=array($value['longitude'],$value['latitude'],$value['wdtype'],$value['start_price']);
            $map_data[$value['rid']]['start_price'] = $value['start_price'];
            $map_data[$value['rid']]['color'] = $map_color[$value['wdtype']];
        }



        //dump($re_data);

        $res_data['data'] = array_values($map_data);
        $res_data['distribution_mode'] = $distribution_mode;

        if(!$_POST['is_wm']){
            //添加行为
            $user_bevavior = new UserBehavior();
            $val = $user_bevavior->add_browse(I('uid'), 13);
        }


        returnApiSuccess($res_data,"数据坐标信息已返回");
    }

    /**
     * TODO 检查是否领取指定类型红包
     */
    public function check_bonus(){

         $bonus_type_id = I("post.bonus_type_id");
         $data = $this->checkBonusIsReceive($bonus_type_id);

         returnApiSuccess(array('action'=>$data['action']), $data['msg']);

    }

    public function checkBonusIsReceive($bonus_type_id)
    {
        if(!is_numeric($bonus_type_id)){
            //处理一次领取多个红包的问题
            $bonus_type_array =  explode(",",$bonus_type_id);
        }else{
            $bonus_type_array = array($bonus_type_id);
        }

        /**
         *查询用户是否有指定红包
         */
        if(empty($bonus_type_array)){
            returnApiError('参数错误:无指定红包类型ID');
        }

        $is_action = false;

        foreach ($bonus_type_array as $key=>$value){
            $bonus_data = M("bonus_type")->where(array("type_id"=>$value))->find();
            $res_data = $this->check_bonus_data($bonus_data);
            if($res_data!==true){
                $data['action'] = 0;
                $data['msg'] = "此红包仅限在：".$res_data." 领取";
                return $data;
            }
            if(gmtime()>$bonus_data['send_end_date']){
                $data['action'] = 0;
                $data['msg'] = '此红包已经停止发放';
                return $data;
            }
            if(gmtime()<$bonus_data['send_start_date']){
                $data['action'] = 0;
                $data['msg'] = '真激动，所有红包都还原封不动的在仓库';
                return $data;
            }

            $res = $this->check_bouns_rank($this->uid,$bonus_data);
            if(!$res){
                $data['action'] = 0;
                $data['msg'] = '当前用户等级不符合领取红包要求';
                return $data;
            }

            $user_bonus_data = M("user_bonus")->where(array("bonus_type_id"=>$value,"user_id"=>$this->uid))->find();

            if($user_bonus_data){
                //已领
            }else {
                //未领
                $is_action = true;
            }
        }
        if($is_action){
            //用户还未领取红包
            $data['action'] = 0;
            $data['msg'] = '光速来领';
        }else{
            $data['action'] = 1;
            $data['msg'] = '已经领取此红包';
        }
        return $data;
    }

    public function autogetbonus($bonus_type_id = null)
    {
        $this->auto_get_bonus($bonus_type_id);
    }

    /**
     * TODO 自动领取指定类型红包
     */
    public function auto_get_bonus($bonus_type_id = null){
        if(empty($this->uid)){
            returnApiError("uid 为空");
        }

        /*$this->uid = mt_rand(1000, 7011);
        $bonus_type_id = 206;*/

        if(empty($bonus_type_id)){
            $bonus_type_id = I("post.bonus_type_id");
        }

        $bonus_data = S('bonus_type_id_data_queue_'.$bonus_type_id);

        if(! $bonus_data) {
            $this->add_bonus_type_array($bonus_type_id);
        }

        if(empty($bonus_type_id)){
            returnApiError("参数错误:无指定红包类型ID");
        }
        
        


        if (check_app_version($bonus_data['android_version'], $bonus_data['ios_version'])) {
            returnApiError('您的APP版本过低，请升级至最新版领取');
        }

        $res_data = $this->check_bonus_data($bonus_data);
        if($res_data!==true){
            returnApiError("此红包仅限在：".$res_data." 领取");
        }

        $res = $this->check_bouns_rank($this->uid, $bonus_data);
        if(!$res){
            if($bonus_data['bouns_user_rank']==2){
                returnApiError('该红包仅限 VIP 领取');
            }
            if($bonus_data['bouns_user_rank']==1){
                returnApiError('该红包仅限 注册用户 领取');
            }
            if($bonus_data['bouns_user_rank']==100){
                returnApiError('该红包仅限 新用户 领取');
            }
        }


        $user_bonus_service = new UserBonusService();

        //加入队列处理
        $user_bonus_service->handleQueue($this->uid, $bonus_type_id, $bonus_data);


    }

    protected function add_bonus_type_array($bonus_type_id)
    {
        if(!is_numeric($bonus_type_id)){
            //处理一次领取多个红包的问题
            $bonus_type_array =  explode(",",$bonus_type_id);
        }else{
            $bonus_type_array = array($bonus_type_id);
        }

        if(empty($bonus_type_array)){
            returnApiError("参数错误:无指定红包类型ID");
        }

        $bonus_cache_id  = implode('_',$bonus_type_array);
        if(S("auto_get_bonus_".$this->uid.'_'.$bonus_cache_id)>0){
            returnApiError("请勿重复操作");
        }else{
            S("auto_get_bonus_".$this->uid.'_'.$bonus_cache_id,999,10);
        }

        $user_bonus = 0;

        $map = array("send_type"=>3,"type_id"=>array('in',$bonus_type_array));
        $bonus_list = M("bonus_type")->where($map)->select();
        if(empty($bonus_list)){
            returnApiError("当前没有可领取的红包");
        }
        foreach ($bonus_list as $key=>$value){
            $user_bonus_data = M("user_bonus")->where(array("bonus_type_id"=>$value['type_id'],"user_id"=>$this->uid))->count();
            if(!empty($user_bonus_data)){
                unset($bonus_list[$key]);
                $user_bonus ++;
            }
        }

        if(count($bonus_list)==0){
            $data['action'] = 1;
            returnApiError("已经领取此红包");
            //returnApiSuccess($data,"已经领取此红包");
        }
        $bonus_array = array();
        foreach ($bonus_list as $key=>$value){
            $bonus_data = $value;
            $res_data = $this->check_bonus_data($bonus_data);
            if($res_data!==true){
                returnApiError("此红包仅限在：".$res_data." 领取");
            }

            $res = $this->check_bouns_rank($this->uid,$bonus_data);
            if(!$res){
                if($bonus_data['bouns_user_rank']==2){
                    returnApiError("该红包仅限 VIP 领取");
                }
                if($bonus_data['bouns_user_rank']==1){
                    returnApiError("该红包仅限 注册用户 领取");
                }
                if($bonus_data['bouns_user_rank']==100){
                    returnApiError("该红包仅限 新用户 领取");
                }
            }

            if (check_app_version($bonus_data['android_version'], $bonus_data['ios_version'])) {
                returnApiError('您的APP版本过低，请升级至最新版领取');
            }

            if($bonus_data['has_effective_days']==1 && $bonus_data['effective_days']>0){
                $end_time = time() + ($bonus_data['effective_days']-1)*24*3600;
                $end_date = date('Y-m-d',$end_time)." 23:59:59";
                $deadline = local_strtotime($end_date); //转换成GMT格林威治时间戳
            }else{
                $deadline = 0;
            }

            $bonus_id_f = M("user_bonus")->where(array("bonus_type_id"=>$bonus_data['type_id'],"user_id"=>0))
                ->getField("bonus_id");
            $bonus_own = M("user_bonus")->where(array("bonus_type_id"=>$bonus_data['type_id'],"user_id"=>$this->uid))
                ->count();
            if($bonus_id_f&&empty($bonus_own)){
                $data['user_id'] = $this->uid;
                $data['get_time'] = gmtime();
                $data['deadline'] = $deadline;
                M("user_bonus")->where(array("bonus_id"=>$bonus_id_f))->save($data);
                $bonus_array[] = $bonus_id_f;

                //新人红包领取缓存
                if (in_array($bonus_id_f, C('NEW_USER_BONUS_ARRAY'))) {
                    S('user_new_bonus_receive_'.$this->uid, 1);
                }

            }else{
                returnApiError("来晚一步，红包发完了");
            }
        }
        $data['action'] = 1;
        $data['bonus_id'] = implode(",",$bonus_array);
        returnApiSuccess($data,"领取成功");
    }

    public function check_bonus_data($bonus_data){
        if(gmtime()<$bonus_data['send_start_date']||
            gmtime()>$bonus_data['send_end_date']){
            return local_date('Y-m-d', $bonus_data['send_start_date'])." - ".
                local_date('Y-m-d', $bonus_data['send_end_date']);
        }else{
            return true;
        }


    }


    /**
     * 检查当前使用红包的用户是否满足等级要求
     * @param $uid
     * @param $bonus_data
     * @return bool
     */
    public function check_bouns_rank($uid,$bonus_data){
        $flag = true;
        $bonus_rank = $bonus_data['bouns_user_rank'];
        if($bonus_rank!=0){
            //获取当前用户等级
            $map = array('user_id'=>$uid);
            $user_rank = M('users')->where($map)->getField('user_rank');
            switch ($bonus_rank){
                case '100':         //用户等级为注册用户且没有下单记录的，为新用户
//                    if($user_rank==1){
                    $order_map = array('user_id'=>$uid,'order_status'=>array('in',array(OS_CONFIRMED,OS_SPLITED)),'shipping_status'=>SS_RECEIVED);
                    $order_count = M('order_info')->where($order_map)->count();
                    if($order_count>C('NEW_USER_ORDER_NUMBER')){
                        $flag = false;
                    }
//                    }else{
//                        $flag = false;
//                    }
                    break;
                default:
                    if($user_rank!=intval($bonus_rank)){
                        $flag = false;
                    }
            }
        }

        return $flag;
    }

    public function purchase_goods_list(){
        $uid = $this->uid;
        $page_num = I("page",1,'int');

        if(empty($uid)){
            returnApiError('uid不能为空');
        }

        //添加行为
        $user_bevavior = new UserBehavior();
        $user_bevavior->add_browse($uid, 36);

        $page_num = intval($page_num);
        $wid = I('wid',C('PURCHASED_NUMBER'),'int');
        if(empty($page_num) || $page_num==0){
            $page_num = 1;
        }

        $purchased_number = C('PURCHASED_NUMBER');
        $order_goods = M('order_goods');

        $count_sql = "SELECT COUNT(*) as count FROM (
                          SELECT COUNT(og.goods_id) as num,o.`user_id`,og.* FROM sdx_order_goods og 
                          left join sdx_order_info o on og.order_id = o.order_id 
                          left join sdx_goods g on g.goods_id=og.goods_id 
                          WHERE o.user_id = ".$uid." AND o.shipping_status = ".SS_RECEIVED." AND o.order_status in(".OS_CONFIRMED.",".OS_SPLITED.") 
                          GROUP BY og.goods_id having COUNT(og.goods_id)  >= ".$purchased_number.") t";
                            //AND g.is_on_sale = 1 AND g.is_delete = 0 AND g.is_alone_sale = 1

        $arcount = $order_goods->query($count_sql);

        $count = current($arcount);

        if($count['count']>0){
            $pagearr = show_page($count['count'], $page_num, C("page_size"));
            if($page_num>=$pagearr['pagecount']){
                $is_last=1;
            }else{
                $is_last=0;
            }

            $map = array(
                'o.user_id'=>$uid,
                'o.shipping_status'=>SS_RECEIVED,
                'o.order_status'=>array('in',array(OS_CONFIRMED,OS_SPLITED)),
                /*'g.is_on_sale'=>1,
                'g.is_delete'=>0,
                'g.is_alone_sale'=>1*/
            );

            $field = "og.goods_id,og.goods_name,COUNT(og.goods_id) as goods_buy_total,g.*";
            $goods_list = $order_goods->alias('og')
                ->field($field)
                ->join('left join '.C('DB_PREFIX').'order_info o on og.order_id = o.order_id')
                ->join('left join '.C('DB_PREFIX').'goods g on g.goods_id=og.goods_id')
                ->where($map)
                ->group('og.goods_id')
                ->having('COUNT(og.goods_id)>='.$purchased_number)
                ->limit($pagearr['firstpage'],$pagearr['pagesize'])
                ->order('goods_buy_total desc')
                ->select();

            $goods_list =  $this->get_goods_data($goods_list,$uid,$wid);
            $result = array('list'=>$goods_list,'is_bottom'=>$is_last);
            returnApiSuccess($result);
        }else{
            returnApiError('常购清单中没有商品');
        }
    }

    private function get_goods_data($goods_list,$uid,$wid){
        foreach($goods_list as $key=>$val){
            $is_booking = D('goods')->is_book_goods($val['goods_id'], $uid);
            if($is_booking){
                $goods_list[$key]['is_booking']='1';
            }else{
                $goods_list[$key]['is_booking']='0';
            }
        }
        $goods_list = D('goods')->convert_goods_info($goods_list,$wid, $uid);

        // 取得优惠活动
        $favourable_list = D('NewCart')->favourable_list_flow($uid,$wid);
        foreach($goods_list as $key=>$val){
            $goods_list[$key]['favourable_list'] = D('goods')->get_goods_favourable_list($favourable_list,$val);
        }

        return $goods_list;
    }

    public function my_invite_list(){
        $uid = $this->uid;
        $page_num = I('post.page');
        if(empty($uid)){
            returnApiError('用户不存在');
        }
        $map = array('uba.is_first_login'=>1,'uba.share_uid'=>$uid);

        $count = D('user_behavior_address')->alias('uba')->where($map)->count('id');
        if($count>0){
            $page_arr = show_page($count,$page_num);

            $user_list = D('user_behavior_address')
                ->alias('uba')
                ->field('uba.uid,uba.add_time,wu.nickname,wu.sex,wu.headimgurl')
                ->join('left join '.C('DB_PREFIX').'wechat_user wu on uba.uid=wu.ect_uid')
                ->where($map)
                ->order(array('uba.add_time'=>'desc'))
                ->limit($page_arr['firstpage'],$page_arr['pagesize'])
                ->select();

            foreach($user_list as $key=>$user){
                $order_map = array(
                    'user_id'=>$user['uid'],
                    'order_status'=>array("in","1,5"),
                    'shipping_status'=>2,
                    'pay_status'=>array("in","2,3")
                );

                $order_count = D('order_info')->where($order_map)->count();
                if($order_count>0){
                    $user_list[$key]['invite_status'] = 2;
                }else{
                    $user_list[$key]['invite_status'] = 1;
                }
                $user_list[$key]['add_time'] = $user['add_time'];
            }
            $return_data['invite_total_num'] = count($user_list);
            $return_data['user_list'] = $user_list;
            $return_data['is_bottom'] = $page_arr['is_bottom'];

            returnApiSuccess($return_data);
        }else{
            returnApiError('暂无邀请用户');
        }
    }


    /**
     * 检测邀请数据，修正老用户邀请数据
     * @param $uid
     * @param $count
     * @return mixed
     */
    public function check_user_invite($uid,$count){
        $sql = "select uid
                  from(
                SELECT uba.uid
                  FROM sdx_user_behavior_address uba
                  left join sdx_order_info o on uba.uid= o.user_id 
                 where uba.is_first_login = 1
                   and uba.share_uid = ".$uid." 
                   and o.order_status in(1, 5)
                   and o.shipping_status = 2
                   and o.pay_status in (2, 3)
                   and uba.add_time>(o.add_time + 8*3600)
                 order by o.order_id ASC) as temp
                 GROUP BY uid";
        $model = M();

        $user_list = $model->query($sql);
        if(!empty($user_list)){
            $uid_list = array();
            foreach($user_list as $key=>$user){
                $uid_list[] = $user["uid"];
            }
            if(count($uid_list)>0){
                $change_map = array('is_first_login'=>1,'uid'=>array('in',$uid_list));
                M('user_behavior_address')->where($change_map)->setField('share_uid',0);
                $map = array('is_first_login'=>1,'share_uid'=>$uid);
                $count = D('user_behavior_address')->where($map)->count('id');
            }
        }

        return $count;
    }

    /**
     * 统计邀请成功总人数
     * @param $uid
     * @return mixed
     */
    public function get_shared_count($uid){
        $sql = "SELECT count(distinct uba.uid) as shared_count
                  FROM sdx_user_behavior_address uba
                  left join sdx_order_info o on uba.uid= o.user_id
                 where uba.is_first_login= 1
                   and uba.share_uid= ".$uid."
                   and o.order_status in (1, 5)
                   and o.shipping_status= 2
                   and o.pay_status in(2, 3)
                   and uba.add_time<(o.add_time+ 8*3600)
                 order by o.order_id ASC;";

        $model = M();
        $res = $model->query($sql);

        $data = current($res);

        return $data['shared_count'];
    }

    public function my_center_info(){
        $uid = $this->uid;
        if(empty($uid)){
            returnApiError('用户不存在');
        }

        $order_type_info = $this->get_order_type_info($uid);

        $user_service_info = $this->get_user_service_info($uid);

        //获取用户分享邀请新用户人数
        $share_page_info = C('SHARE_PAGE_INFO');
        $map = array('is_first_login'=>1,'share_uid'=>$uid);

        $share_invited_num = D('user_behavior_address')->where($map)->count('id');
        if($share_invited_num>0){
            $share_invited_num = $this->check_user_invite($uid,$share_invited_num);
        }
        $share_page_info['share_invited_num'] = $share_invited_num;
        $share_page_info['share_invited_success_num'] = $this->get_shared_count($uid);
        $share_page_info['share_invited_reg_num'] = strval($share_page_info['share_invited_num']-$share_page_info['share_invited_success_num']);

        $res['order_type_info'] = $order_type_info;
        $res['user_service_info'] = $user_service_info;
        $res['share_page_info'] = $share_page_info;

        returnApiSuccess($res);
    }

    private function get_user_service_info($uid){
        //收藏商品数
        $user_service_info = array();
        $user_service_info['collect_num'] = M("collect_goods")->where(array("user_id"=>$uid))->count();

        //常购清单商品数
        $purchased_number = C('PURCHASED_NUMBER');
        $order_goods = M('order_goods');

        $count_sql = "SELECT COUNT(*) as count FROM (
                          SELECT COUNT(og.goods_id) as num,o.`user_id`,og.* FROM sdx_order_goods og 
                          left join sdx_order_info o on og.order_id = o.order_id 
                          left join sdx_goods g on g.goods_id=og.goods_id 
                          WHERE o.user_id = ".$uid." AND o.shipping_status = ".SS_RECEIVED." AND o.order_status in(".OS_CONFIRMED.",".OS_SPLITED.") AND g.is_on_sale = 1 AND g.is_delete = 0 AND g.is_alone_sale = 1 
                          GROUP BY og.goods_id having COUNT(og.goods_id)  >= ".$purchased_number.") t";

        $arcount = $order_goods->query($count_sql);

        $frequently_goods = current($arcount);
        $user_service_info['frequently_goods_num'] = $frequently_goods['count'];
        return $user_service_info;
    }
    private function get_order_type_info($uid){
        $order_type_info_num = array();
        $order_info = M('order_info');

        //未付款订单数
        $map_no_pay = array('user_id'=>$uid,'order_status'=>OS_UNCONFIRMED,'pay_status'=>PS_UNPAYED);
        $order_type_info_num['no_pay_num'] = $order_info->where($map_no_pay)->count();
        //待收货订单数
        $map_no_pay = array('user_id'=>$uid,'order_status'=>array('in',array(OS_CONFIRMED,OS_SPLITED)),'shipping_status'=>array('neq',SS_RECEIVED));
        $order_type_info_num['wait_received_num'] = $order_info->where($map_no_pay)->count();
        //待评价订单数
        $sql = "select count(order_id) as nums from sdx_order_info where user_id=".$uid." and order_sn not in(select order_sn from sdx_comment) and shipping_status=".SS_RECEIVED." and order_status in(".OS_SPLITED.",".OS_CONFIRMED.")";
        $pending_comment = $order_info->query($sql);
        $pending_comment = current($pending_comment);
        $order_type_info_num['pending_comment_num'] = $pending_comment['nums'];
        //未回复的售后工单数量
        $workorder_modell = new WorkorderModel();
        $order_type_info_num['work_order_num'] = $workorder_modell->get_workorder_number($uid);
        return $order_type_info_num;
    }

    /**
     *  分享領取紅包，并返回
     */
    public function share_bonus(){
        $order_sn = I("post.order_sn");
        $is_check = I("post.is_check");
        $order_id = I("post.order_id");
        if(empty($order_id)){
            $order_id = M("order_info")->
            where(array("order_sn"=>$order_sn,"pay_status"=>array("in","2,3")))
                ->getField("order_id");
        }

        if(empty($order_id)){
            returnApiError("订单错误/未支付");
        }
        if($is_check!=1){
            if(S("share_bonus_".$this->uid)>0){
                returnApiError("请勿重复操作");
            }else{
                S("share_bonus_".$this->uid,999,10);
            }
        }

        $is_action = false;
        $is_action_text = 0;



        $order_share_bonus = M("order_share_bonus")->where(array("order_id"=>$order_id,"user_id"=>$this->uid))->getField("bonus_id",true);

        $order_info = M("order_info")->where(array("order_id"=>$order_id))
            ->field("user_id,pay_time")->find();
        $pay_time = $order_info['pay_time']+28800;
        if(time()<1514217600&&time()>1514131200&&
            $pay_time<1514217600&&$pay_time>1514131200){
            $is_action = true;
            $is_action_text = 1;
        }

        $wechat_user = M("wechat_user")->where(array("ect_uid"=>$order_info['user_id']))->find();

        $nickname = $wechat_user['nickname'];        //名称
        $headimgurl = $wechat_user['headimgurl'];    //头像

        if(!empty($order_share_bonus)){
            returnApiSuccess(
                array(
                    "bonus_id"=>implode(",",$order_share_bonus),
                    "images"=>$headimgurl,
                    "is_action"=>$is_action_text,
                    "name"=>$nickname)
            );
        }elseif ($is_check ==1){
            returnApiSuccess(
                array("images"=>$headimgurl,
                    "name"=>$nickname,
                    "is_action"=>$is_action_text
                ),
                "还未领取红包");
        }

        if($is_action){
            //圣诞节期间，调用此方法
            $this->christmas_activity($order_id);
        }

        $is_first = M("order_info")->where(array("user_id"=>$this->uid,"order_status"=>array("neq",2),"pay_status"=>array("in","2,3")))->count();
        if($is_first==0){
            //首次登录 122、61、64、65（ ⼀键领取四个）
            //$this->auto_get_bonus('122,61,64,65',true);
            $first_share_bonus = M("order_share_bonus")->where(array("user_id"=>$this->uid))->count();
            $first_bonus = M("user_bonus")->where(array("user_id"=>$this->uid,"bonus_type_id"=>122))->count();
            if(!empty($first_share_bonus)||!empty($first_bonus)){
                //已领取过红包
                $this->auto_get_bonus_new('142',$order_id);
            }else{
                //新用户
                $this->auto_get_bonus_new(C("NEW_USER_BONUS"),$order_id);
            }

        }else{
            //多次登录 137、138、139、140、141、142（随机领取其中⼀个）
            $bonus_array = array(307,308,309,310,311,322);
            //$bonus_array = array(145,144,143,140,141,142);
            //rand(0,5);
            $bonus_type_id = $bonus_array[rand(0,5)];
            $this->auto_get_bonus_new($bonus_type_id,$order_id);
        }
    }

    /**
     * 圣诞活动领取红包，仅限在圣诞期间可用
     * @param $order_id
     */
    public function christmas_activity($order_id){
        $bonus_100 = 437;
        $bonus_50 = 438;
        $bonus_30 = 441;
//        $bonus_100 = 177;
//        $bonus_50 = 178;
//        $bonus_30 = 179;
        $now_bonus = 0;
        $now_bonus_rand = rand(1,100);
        if($now_bonus_rand<6){
            //发放100元红包 100/179
            //判断当前是否还剩余此类红包
            $user_bonus = M("user_bonus")->where(
                array("bonus_type_id"=>$bonus_100,"user_id"=>array("eq",0))
            )->count();
            if($user_bonus){
                $now_bonus = $bonus_100;
            }else{
                //已用完
                $now_bonus = $bonus_30;
            }
        }elseif($now_bonus_rand>6&&$now_bonus_rand<21){
            //发放50元红包  50/129
            $user_bonus = M("user_bonus")->where(
                array("bonus_type_id"=>$bonus_50,"user_id"=>array("eq",0))
            )->count();
            if($user_bonus){
                $now_bonus = $bonus_50;
            }else{
                //已用完
                $now_bonus = $bonus_30;
            }
        }else{
            //发放30元红包  30/79
            $now_bonus = $bonus_30;
        }
        $this->auto_get_bonus_new($now_bonus,$order_id);
    }


    /**
     * 获取指定订单所分享出的红包【看朋友们运气】
     */
    public function get_order_bonus(){
        $order_sn = I("post.order_sn");
        $order_id = I("post.order_id");
        if(empty($order_id)){
            $order_id = M("order_info")->where(array("order_sn"=>$order_sn))->getField("order_id");
        }
        $page = I("post.page");
        if(empty($page)||$page<1){
            $page = 1;
        }
        $start_lim = ($page-1)*20;
        $order_share_bonus = M('order_share_bonus')->where(array("order_id"=>$order_id))->limit($start_lim,20)->order('id desc')->select();
        if(count($order_share_bonus)==20){
            $is_bottom = 0;
        }else{
            $is_bottom = 1;
        }
        $me = array(
            "谢大包，又可以买买买啦！",
            "没想到我长得这么萌，运气还这么好！",
            "好基友有福同享，有包同抢！",
            "抢到啦，从此不用控制寄几啦！",
            "妈妈再也不用担心我吃土啦~"
        );
        $user_id = array();
        foreach ($order_share_bonus as $key=>$value){
            if(!in_array($value['user_id'],$user_id)){
                $user_bonus = M("user_bonus")->where(array("bonus_id"=>$value['bonus_id']))->find();
                $bonus_type = M("bonus_type")->where(array("type_id"=>$user_bonus['bonus_type_id']))->find();
                $order_share_bonus[$key]['type_money'] = $bonus_type['type_money'];
                $order_share_bonus[$key]['type_name'] = $bonus_type['type_name'];       //红包钱
                $order_share_bonus[$key]['deadline'] = $user_bonus['deadline'];

                $wechat_user = M("wechat_user")->where(array("ect_uid"=>$value['user_id']))->find();

                $order_share_bonus[$key]['nickname'] = $this->get_thumbnail_name($wechat_user['nickname']);        //名称
                $order_share_bonus[$key]['headimgurl'] = $wechat_user['headimgurl'];    //头像
                $order_share_bonus[$key]['text'] =$me[rand(0,4)];    //描述文字
                $user_id[] = $value['user_id'];
            }else{
                unset($order_share_bonus[$key]);
                $user_bonus = M("user_bonus")->where(array("bonus_id"=>$value['bonus_id']))->find();
                $bonus_type = M("bonus_type")->where(array("type_id"=>$user_bonus['bonus_type_id']))->find();

                foreach ($order_share_bonus as $key2=>$value2){
                    if($value['user_id'] == $value2['user_id']){
                        $order_share_bonus[$key2]['type_money'] += $bonus_type['type_money'];
                    }
                }
            }

        }
        returnApiSuccess(array("data"=>array_values($order_share_bonus),"is_bottom"=>$is_bottom));
    }
    private function get_thumbnail_name($name){
        if(mb_strlen($name,'utf-8')>11){
            $len = mb_strlen($name,'utf-8');
            $str1 = mb_substr($name,0,3,'utf-8');
            $str2 = mb_substr($name,$len-4,4,'utf-8');
            $name=$str1.'****'.$str2;
        }
        return $name;
    }
    /**
     * 获取红包详情，可多个，多个以，分割
     */
    public function get_bonus_info(){
        $bonus_id = I("post.bonus_id");
        $bonus_array  = explode(",",$bonus_id);
        $bonus_array_list = array();
        foreach ($bonus_array as $key=>$value){
            $user_bonus = M("user_bonus")->where(array("bonus_id"=>$value))->find();
            $bonus_type = M("bonus_type")->where(array("type_id"=>$user_bonus['bonus_type_id']))->find();
            $bonus_array_list[$key]['type_name'] = $bonus_type['type_name'];       //红包钱
            if($user_bonus['deadline']){
                $bonus_array_list[$key]['deadline'] = $user_bonus['deadline'];
            }else{
                $bonus_array_list[$key]['deadline'] = $bonus_type['use_end_date']+28800;
            }

            $bonus_array_list[$key]['money'] = $bonus_type['type_money'];
            $bonus_array_list[$key]['id']= $value;
        }
        returnApiSuccess(array("data"=>$bonus_array_list));
    }

    /**
     * TODO 自动领取指定类型红包
     */
    public function auto_get_bonus_new($bonus_type_id = null,$share_order){
        if(empty($bonus_type_id)){
            $bonus_type_id = I("post.bonus_type_id");
        }
        if(!is_numeric($bonus_type_id)){
            //处理一次领取多个红包的问题
            $bonus_type_array =  explode(",",$bonus_type_id);
        }else{
            $bonus_type_array = array($bonus_type_id);
        }

        if(empty($bonus_type_array)){
            returnApiError("参数错误:无指定红包类型ID");
        }

        $bonus_cache_id  = implode('_',$bonus_type_array);
        if(S("auto_get_bonus_".$this->uid.'_'.$bonus_cache_id)>0){
            returnApiError("点击的太快了");
        }else{
            S("auto_get_bonus_".$this->uid.'_'.$bonus_cache_id,999,10);
        }

        $map = array("send_type"=>3,"type_id"=>array('in',$bonus_type_array));
        $bonus_list = M("bonus_type")->where($map)->select();
        //dump(M("bonus_type")->getLastSql());
        if(empty($bonus_list)){
            returnApiError("当前没有可领取的红包");
        }
        $i = 0;
        $bonus_array = "";
        foreach ($bonus_list as $key=>$value){
            $bonus_data = $value;

            if($bonus_data['has_effective_days']==1 && $bonus_data['effective_days']>0){
                $end_time = time() + ($bonus_data['effective_days']-1)*24*3600;
                $end_date = date('Y-m-d',$end_time)." 23:59:59";
                $deadline = local_strtotime($end_date); //转换成GMT格林威治时间戳
            }else{
                $deadline = 0;
            }


            $bonus_id_f = M("user_bonus")->where(array("bonus_type_id"=>$bonus_data['type_id'],"user_id"=>0))
                ->getField("bonus_id");

            if($bonus_id_f){
                $data['user_id'] = $this->uid;
                $data['get_time'] = gmtime();
                $data['deadline'] = $deadline;
                M("user_bonus")->where(array("bonus_id"=>$bonus_id_f))->save($data);
                    //分享订单红包，写入额外数据
                $share_data['order_id'] = $share_order;
                $share_data['user_id'] = $this->uid;
                $share_data['bonus_id'] = $bonus_id_f;
                $share_data['get_time'] = gmtime();
                M("order_share_bonus")->add($share_data);
                if($i!=0){
                    $bonus_array .=",".$bonus_id_f;
                }else{
                    $bonus_array = $bonus_id_f;
                }
                $i++;
            }else{
                //returnApiError("来晚一步，红包发完了");
            }
        }
        $user_info = M("order_info")->where(array("order_id"=>$share_order))->getField("user_id");
        $wechat_user = M("wechat_user")->where(array("ect_uid"=>$user_info))->find();

        $data['nickname'] = $this->get_thumbnail_name($wechat_user['nickname']);        //名称
        $data['headimgurl'] = $wechat_user['headimgurl'];    //头像
        $data['action'] = 1;
        $data['bonus_id'] = $bonus_array;
        returnApiSuccess(array("data"=>$data),"领取成功");

    }

    /**
     * 我的页面新增活动版块，根据广告位有无内容显示。
     */
    public function get_my_info_ad(){
        $where['enabled'] = 1;

        if(PLATFORM_TYPE=='formal'){
            $where['position_id'] = 321;
        }else{
            $where['position_id'] = 316;
        }

        $where['start_time'] = array("lt",gmtime());
        $where['end_time'] = array("gt",gmtime());

        $ad_list = M("ad")->field("ad_name,ad_link,ad_code")->where($where)->select();
        foreach ($ad_list as $key=>$value){
            $ad_list[$key]['ad_code'] = "https://image.shidexian.com/data/attached/afficheimg/".$value['ad_code'];
        }
        returnApiSuccess(array("data"=>$ad_list),"我的页面广告列表");
    }

    //是否用户指引提示
    public function show_user_guide(){
        $app_type = I('post.app_type');
        $uid = I('post.uid');

        $is_showed = S('is_show_user_guide_'.$app_type.'_'.$uid);

        if(empty($is_showed)){
            $is_showed = 0; //没有显示过，需要显示
            S('is_show_user_guide_'.$app_type.'_'.$uid,1);  //保存已显示状态
        }

        $res = array('is_showed'=>$is_showed);

        returnApiSuccess($res);
    }

    //超时免单规则
    public function get_free_single_rule(){
        $rule = "1.本项服务限特定物流配送区域及特定配送时段有效，在服务有效配送区域内，若订单实际送达时间超出预选时间，免单生效，免单金额在1-3个工作日内补偿到订单账户余额，补偿金额以订单实际支付金额（若订单发生退款以退款后金额）为准。
2.为保证真实用户权益，本项服务仅限当面验货及确认收货订单有效。
3.订单中使用的红包不在本项服务补偿范畴。
4.订单选择的配送时间以订单付款顺序为准，延时订单将会自动顺延至下个配送时间段，本项服务有效性以实际配送时间为准。若订单配送时间顺延后不在本项服务有效时段内，则订单不参与本项服务。
5.违规获取补偿的订单，食得鲜有权取消补偿及关闭订单交易。
6.本项服务最终解释权归食得鲜所有。";
        $rule_arr = array(
'1.本项服务限特定物流配送区域及特定配送时段有效，在服务有效配送区域内，若订单实际送达时间超出预选时间，免单生效，免单金额在1-3个工作日内补偿到订单账户余额，补偿金额以订单实际支付金额（若订单发生退款以退款后金额）为准。',
'2.为保证真实用户权益，本项服务仅限当面验货及确认收货订单有效。',
'3.订单中使用的红包不在本项服务补偿范畴。',
'4.订单选择的配送时间以订单付款顺序为准，延时订单将会自动顺延至下个配送时间段，本项服务有效性以实际配送时间为准。若订单配送时间顺延后不在本项服务有效时段内，则订单不参与本项服务。',
'5.违规获取补偿的订单，食得鲜有权取消补偿及关闭订单交易。',
'6.本项服务最终解释权归食得鲜所有。');
        returnApiSuccess(array('rule'=>$rule, 'rule_arr'=>$rule_arr));
    }

    /**
     * 按照地址查询所属仓库
     */
    public function check_area_by_address(){

        $longitude = I("post.longitude");
        $latitude = I("post.latitude");

        if(empty($longitude)||empty($latitude)){
            returnApiError("经纬度不正确");
        }

        $distribution_data =
            D('Useraddress')->get_distribution_by_gps($longitude,$latitude);


        returnApiSuccess($distribution_data);
    }

}